text:
Light sensor always getting max value
I have build a simple voltage divider with a light resistor and a 5.6k resistor. I am reading the input on A0 on my arduino board but it is almost always at 1023, independent of light. If I cover it it might go down to 1020 but not more than that.
Do I have to use a greater resistor than 5.6k to achieve more difference in the sensor?
The light sensor is similar to this: http://www.ebay.com/itm/20x-5549CDS-Photo-Light-Dependent-Sensitive-Resistor-Photoresistor-LDR-Photocell-/281425650814?pt=LH_DefaultDomain_0&hash=item418646a47e
I think that the resistance is pending between 1k-10k.
The circuit is like this image:

Where Vin is 5V from the arduino. R1 is the light sensor, R2 is 5.6k and Vout is connected to A0.

Can you show a diagram of your exact circuit?

A pointer to the datasheet for the photo-resistor would help, too. At the very least, we'd need to know its resistances when dark and bright.

5.6k sounds good. Is A0 connected between LDR and Resistor? Can you check that LDR works using an Ohm meter?

A circuit is essential. A description in words in the absence of a circuit is a logical minimum if you actually want an answer. LDR should go from eg A0 to Vcc and resistor from A0 to ground or vice versa - is that what you did? Where did you get the information? Datasheet for LDR? (There are zillions of types). ...

I updated the question now!

Have you tested the voltages and resistances with a Multimeter?

What have you selected as the analog reference? And if 'external', what is connected to the Vref pin?
For the LDR resistances of 10K and 1K, you  Vout should be ~ 1.8v at 10K, and ~ 4.2v at 1K, and giving A/D readings of somewhere around 370 counts and 860 counts, respectively, with a 5v analog reference.
If your analog reference selected to the 1.1v internal reference, either LDR resistance should give you the max reading, but an LDR = 20K could give just over a volt and pretty close to the reading you're getting.

Judging by a datasheet (that I found on the web) that has a resistance of:

100 k to 200 k in the light
1 M in the dark

Given that Vout =  Vin * R2 / (R1 + R2) we can work out:
Light:
Vout = 5 * 200000 / (200000 + 5600) = 4.86 V

Dark:
Vout = 5 * 1000000 / (1000000 + 5600) = 4.97 V

Do I have to use a greater resistor than 5.6k to achieve more difference in the sensor?

Yes, I would measure the resistance in the light, and choose a similar resistor for the other side of the voltage divider. So if you measure 100 k on the sensor, another 100 k will at least divide the voltage in two nicely.


text:
Error in Compiling
The error shown is
C:\Users\SIDDHA~1\AppData\Local\Temp\build3397782103973366883.tmp/core.a(Tone.cpp.o): In function `__vector_7':
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Tone.cpp:536: multiple definition of `__vector_7'
C:\Users\SIDDHA~1\AppData\Local\Temp\build3397782103973366883.tmp\IRremote\IRremote.cpp.o:C:\Users\Siddharth Yadav\Documents\Arduino\libraries\IRremote/IRremote.cpp:361: first defined here
collect2.exe: error: ld returned 1 exit status

Why is this happening?
The code is:
#include <IRremote.h>

const int echo = 7;// connected to ultrasonic sensor's echo
const int trig = 8;// connected to ultrasonic sensor's trig
const int Right1 = 10;
const int Right2 = 11;
const int Left1 = 12;
const int Left2 = 9;// change this to any other pin; except pin 13
const int buzzer = 5;
const int rightIR = 3;// change here
const int leftIR = 2;// change here
int RECV_PIN = 4;
const int forward = 51;
const int backward = 36;
const int left = 19;
const int right = 0;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  pinMode(buzzer, OUTPUT);
  pinMode(echo, INPUT_PULLUP);
  pinMode(rightIR, INPUT_PULLUP);
  pinMode(leftIR, INPUT_PULLUP);
  pinMode(trig, OUTPUT);
  pinMode(Right1, OUTPUT);
  pinMode(Right2, OUTPUT);
  pinMode(Left1, OUTPUT);
  pinMode(Left2, OUTPUT);
  sing(1);
  Serial.begin(9600);
 irrecv.enableIRIn(); // Start the receiver

}

void loop() {
  digitalWrite(13, HIGH);
  if (calcDistance() > 30 && !isRight() && !isLeft())
  {
    if (irrecv.decode(&results))
    {
      Serial.println(results.value, HEX);
      irrecv.resume(); // Receive the next value
      delay(50);
    }
    else {
      moveForward();
    }

  }
  else
  {
    delay(10);
    int dist = calcDistance();
    if (dist < 30 && isLeft() && isRight())
    {
      Serial.println("Moving backward");
      tone(buzzer, 4699, 10);
      moveBackward();
      delay(1000);
    }
    else if (isLeft())
    {
      turnRight();
      digitalWrite(13, LOW);
      tone(buzzer, 104, 10);
      Serial.println("Turning Right");
    }
    else if (isRight())
    {
      turnLeft();
      digitalWrite(13, LOW);
      delay(300);
      tone(buzzer, 880, 10);
      Serial.println("Turning LEft");
    }
    else if (dist < 30)
    {
      turnRight();
      digitalWrite(13, LOW);
      tone(buzzer,  104 , 10);
      Serial.println("Turning Right");
    }

  }

  delay(20);
}

Can you get a more readable shot of the messages? Or cut-and-paste them? This image is pretty difficult to read.

C:\Users\SIDDHA~1\AppData\Local\Temp\build3397782103973366883.tmp/core.a(Tone.cpp.o): In function __vector_7': C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Tone.cpp:536: multiple definition of __vector_7'
C:\Users\SIDDHA~1\AppData\Local\Temp\build3397782103973366883.tmp\IRremote\IRremote.cpp.o:C:\Users\Siddharth Yadav\Documents\Arduino\libraries\IRremote/IRremote.cpp:361: first defined here
collect2.exe: error: ld returned 1 exit status

As the error message says you have multiple definitions of __vector_7 which is defined in: IRemote.cpp:361 and Tone.cpp:536
Tone.cpp is arduino standart lib. If IRemote is a lib of yours then you should edit the cpp file and change the symbol to sth else.

The IRemote.cpp and Tone.cpp would be using the same interrupt vector. I believe it's ISR(TIMER5_COMPA_vect) {

You could. I don't think it's the best solution, but go to Tone.cpp and comment the ISR(TIMER5_COMPA_vect) { like /*ISR(TIMER5_COMPA_vect)*/void XunusedX(void) {. And be sure to never use any function from ...
You could also try to find a way on how not to invoke Tone.h with core.a. include <Tone.h> could be replaced with //include <Tone.h>
You could use another timer in IRRemote.h

This answer is better than mine :)

source: Stack Exchange

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

sort: votes


text:
How to control Arduino robot wirelessly?
I have a few potentiometers connected to analog inputs in an Arduino UNO. These are then processed and then the servo motors start moving to move the bot.
I would like to keep the motors with the uno and send signals from the pots to the uno. I do not want to use a laptop or another arduino as the remote control. However.. XBEE and other related stuff will do... Thanks
Edit- The wireless solution has to cover a long range preferrably 1 mile.(I dont think I will get any that will cover a mile but I'll give it a try.)
Edit 2- I have 8 servos and 4 potentiometer. I don't necessarily need an xbee. However it may be used.

Do you have any ideas of how to start this, or are you hoping someone else will do it all for you?

I have googled all over and nothing seems to address what I need.... BTW - I am 13 years old

Nothing will address all of what you need. Build it up piece by piece.

I think this guy did something similar. E.g. XBee-PRO® 900HP has 4 ADC pins. Personally I'd use a second arduino to read the pots and send the data over e.g. IR. Cheaper that 2 XBees. Best of luck.

$150 will get you an 8 channel RC radio and receiver, and you will get about 3/4 mile out of it. Anything more will take a ham license to legally operate. Why would you use an Arduino at all?
http://www.ebay.com/itm/Spektrum-DX8-and-AR8000-/111651209735

@Spiked3 - an RC set like that is basically a 2.4 GHz transceiver chip and the functional equivalent of an Arduino, on each end.  The only real arguments against the poster's idea are the complication of DIY vs. an off-the-shelf solution, and the price/size/power premium of an Arduino vs. a comparable bare microcontroller.  NRF24L01+ won't have quite the desired range, but is used a lot in DIY projects of this sort.

@Chris Stratton  Oh, really? Well if is using 8 servos on a 6 pwm pin UNO he must be pretty smart, so ok.

There are many different solutions for doing so.  Remember you only need to output one PWM pulse at a time.

A 13 year old programming an embedded device? Good luck to you, if you conquer it you will be years ahead of your age group.
What you need to understand are the fundamentals; how can you transmit a 'pot' over an XBee? That is an electronics question, start there. You will find that another arduino or laptop is probably required. The XBee itself requires some sort of host adapter, and it might as well be another Arduino since something has to electronically read the 'pots'.
Then you need to develop your own protocol for signals sent between the 2 Arduino (over XBee or on a serial wire , it is the same).  There are many already out there, but they assume you know the basics before you use them (eg firmata). This is the basics.
The fact that your google results showed nothing similar is probably a good indication it can not be done as you had hoped.
update: I like @gerben comment, but even as an advanced person, I would find it challenging.

You can use so many methods to achieve it,as you are a newbie.i would prefer bluetooth and an android app.use bluetooth hc-05 module and use an android app to control.use this app and send string and control arduino.
https://play.google.com/store/apps/details?id=mobi.dzs.android.BLE_SPP_PRO&hl=en

You need to find a way to do this without having individual wireless communication from each pot. There are boards that can communicate wirelessly that are small, however, most of these are around the size of a quarter developed by an electrical engineer. This presents two problems, first the wireless modules will be too big, second, you will need to do a lot of work before you have the experience necessary  to build something like this. I recommend changing a design decision.
Thus, in order to help you further we will need to know more information about your setup.

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


text:
How to interface DS1801 digital resistor with Arduino DUE SPI interface? What clock rate so use?
I am trying to program a digital resistor and set it's wiper resistance. The general circuit looks a little like this where "pot" represents the Maxim DS1801 digital resistor and DUE is, of-course the 3.3v Arduino DUE.
POT       DUE
CLk ----> SCK
D    ----> MOSI
RST ----> CS (ChipSelect) (PIN10)

Now so far, I have sucessfully been able to interface with the DS1801, but I am having issues determining how to properly set the wiper resistance values. The DS1801 datasheet says the it accepts a 16bit input and from application example online it looks like the values range from 0 to 64. Here is my code:
// include the SPI library:
#include <SPI.h>

// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;
int mute = 64;
int loud = 63;
int soft = 0;

void setup() {
  // set the slaveSelectPin as an output:
  pinMode (slaveSelectPin, OUTPUT);
  // initialize SPI:
  SPI.setBitOrder(LSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(slaveSelectPin,SPI_CLOCK_DIV8);
  SPI.begin();
  delay(10);
   digitalPotWrite(mute, mute);
}

void loop() {

  // Raise the volume from off to loud
for(int i = 0; i <= 63; i++){
  digitalPotWrite(i, i);
  delay(5);
    }
  }

void digitalPotWrite(int left, int right) {
  // take the SS pin low to select the chip:
  digitalWrite(slaveSelectPin, HIGH);
  //  send in the address and value via SPI:
  SPI.transfer(left);
  SPI.transfer(right);
  // take the SS pin high to de-select the chip:
  digitalWrite(slaveSelectPin, LOW);
}

I THINK my issue lies with setting the clock rate for the DS1801. The data sheet say the chip runs at 10MHz which is why I wrote
SPI.setClockDivider(slaveSelectPin,SPI_CLOCK_DIV8);

to divide the 84MHz default speed down to 10MHz.
Anyone have suggestions on why my code is not working??? At the moment, I have LED's connected to chip with series resistors to limit current below 2mA. The resistors just blink randomly with the code posted above.

10MHz is too high to have flapping around in the breeze. Show your circuit setup.

I'm not exactly sure what you mean by that? lol   ... Okay, I'll go snap a picture of the circuit and update my post. Why would 10MHz be too high if that's what it says in the datasheet? I don't doubt you, I'm just wondering thats all!   :)

Poor wiring can turn a 10MHz signal into a dog's breakfast, so extra care must be taken when routing such.

Alright, I threw up some pictures, hopefully you can make that out.... essentially, blue is the bit line (D - MOSI), white is the 10MHz clock, and green is Chip Select (or RESET as the datasheet calls it)

Well, it turns out that apparently my issue was not having the AGND pin hooked up. In addition to that, I was trying to switch the wiper resistance value too quickly. By putting at least a 10ms delay between calls, it works much better.
Also, it does seem to work even at 10MHz just fine...

There is no way in hell you're going to get a 10MHz signal down that line. Shorten it to 3 inches total maximum and reduce the clock rate to 2MHz or lower. It is possible to get a 10MHz signal through, but you'd need to switch to twisted pair wiring and proper termination to even begin to have a chance to get it to work.


text:
Sending values to an Arduino Yun across different networks
I have quite a lot of experience with Arduino but have recently been faced with a challenge that has stumped me. The project is to create a robot that can be controlled from a separate network than it is on. I had the idea of using the Yun board to receive the values. Does anyone know a way I could have a computer send data to a Yun on a different network? (Maybe through a website?)

What are the separate networks, how are they connected?

One is my home network, and the other is a network at my workplace. Otherwise they are not connected

This is a very open ended question. What have you tried or have in mind to try? Add some more details and you may get a better response.

I have accomplished this, first by reading this article on controlling a Yun through a web-browser on the same network. From there it was a matter of allowing my Yun to be accessed externally (setting up port-forwarding on my router) and changing a few lines of code to reflect the new location reference.
All the necessary files and code are included under the heading "Project Files" in the above link and no modification is needed to get it working within the same network. That said, I had to convert the two .jpg files to .png (and change the filenames in index.html) - I don't know why they wouldn't show up in my browser.
In brief:
The Yun hosts a webpage (index.html) which contains some indicators and control inputs. These objects are linked to the 32u4 using Bridge and the REST API - nothing special. The bulk of the html code is for visual purposes, and the actual REST calls are nice and simple.
What is good is that the webpage can be accessed from anywhere with the right jiggery-pokery, and with a little more determination can be hosted from anywhere.
External Access
Once you have that working, you need to do the following to allow access externally. I tested this using my smartphone - disconnected from my home WiFi of course - to ensure the link was over the Internet, not intranet.
1) Set up port forwarding and a static IP for the Yun. This is the fundamental step if you simply want to control your Yun over the Internet. However, I can't actually tell you how to do this because I don't know what equipment you have! Information is all over Google for setting up both DHCP static IP and port forwarding.
2) Get a static IP from your ISP for your home/work, or set up a Dynamic DNS service (these people offer it free, but I've never actually needed to use an external service). Most commercial ISPs tend to dish out static IPs, but that's no guarantee that yours will.
3) Access your Yun with a browser via: http://YOUR.IP.ADD.RES:PORT/arduino/<SketchName>.
External Hosting
If you want to host the webpage on something other than the Yun, you can! You will of course need a server to host this, either your work's central server or an external hosting service. You'll need to change some more lines in the code:
1) In the Yun sketch change server.ListenOnLocalhost(); to server.noListenOnLocalhost(); - the subtle difference is the 'no', and is essential for external control. Sorry, that's incorrect without a little more explanation than is required at the moment to answer your original question.
2) In the .html file, you need to change each instance of:
server = "/arduino/<SOMETHING>";

to
server = "YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";

If you have the REST password set to ON then you have to incorporate the username/password in there too:
server = "username:password@YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";

There are three occurences in the original file, so be sure to catch them all.
3) When making changes to the .html file, make sure you re-upload it to the external host, not the Yun - that mistake took me hours to figure out.
A little more...
While searching for the URL of the article in the opening paragraph I found this atricle on a similar theme. It looks to have plenty of information although I haven't read it yet fully yet; I've been busy writing an answer on Stack Exchange. External Access should be no different, and if you want the 'External Hosting' version you just need to find any line that references the 'server' as "/arduino/..." and change it to "YOUR.IP.ADD.RES:PORT/arduino...".

You havent mentioned what exactly your robot does, for now I am going to assume it is something as simple as switching on a light etc and not something like a rover.
The easiest way would be to make the YUN read from a db (like mysql, etc.) and depending on the value perform a task.
For example, you could have a row called light, if the value of it is 1 then turn on the light else turn off the light
The problem you are going to face is the power consumption as you will constantly be polling from the database. You could also look into push notifications ( I am not sure if it is applicable here)
You could also look into creating a private VPN and connecting the YUN and your other devices to it and then control it.

Basically your yun is a linux box with a arduino connected to it on port /dev/ttyATH0.
If you know linux that should answer all your questions about what is possible.
I have setup my own bridge and communicate via html to my robot using cgi script and lua.
I have demoed this on a web contest and you can see it in action on this video from 15:25 onwards https://www.youtube.com/watch?v=q0CnB7Yzpfg&index=3&list=PLCSjf7QmP3TCOLIw0lMPbwHtKrO-nwfKG


text:
Sending SMS once with arduino GPRS SIM900 if an input is HIGH
I faced a problem to send 1 SMS if an input is HIGH and if it is LOW no SMS will be sent. The code not working, just sends SMS when I turn the GPRS on and after that nothing happens.
Please check this link to see the code : the code
Thank you for helping in advance.

Please avoid laziness and repost the complete question here, rather than asking everyone to go to another SE site to look at it; thanks.

repost the complete question here - AKA cross-posting. Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site? - answer is NO.

You need to attach an interrupt to the pin which is getting HIGH and then the function connected to the interrupt will have the code to send the SMS.
Just init the GPRS with connecting to the network then just wait for the interrupt to send anything.


text:
Why does the pin 2 of arduino Mega stay always HIGH?
Without declaring the pin 2 as INPUT or OUTPUT, it remains constantly HIGH. Can anyone explain why is it so?

Pin 2 connects to the controller's PE4, which is a GPIO pin, which can also be used for PWM. You should be able to use it either as input or output, and both high and low. It could be that setup initializes it as output high, while you would usually have uninitialized pins as input.

Have you tried to make it low, or make it input?
digitalWrite(2, LOW);

should make it low, while
pinMode(2, INPUT);
int pin2Status = digitalRead(2);
digitalWrite(13, pin2Status);

will copy the status of pin 2 to the on-board LED.


text:
arduino sketch on Win7 vs. MAC op system?
I have a friend who is just getting started with Arduino UNO.  He downloaded a sketch and is using a UNO on Mac OS.  He loaded the sketch and verified.  it comes up with errors.  He sent me the same sketch and i opened it under Win7 arduino software.  verified, and it says it is fine.  i made an arduino file and emailed it back to him.  he is still getting the same errors.  can anyone help and let me know what is wrong?  i am not a MAC expert and wonder why  this works in win and not MAC????????  appreicate any help anyone can give me

Can you post the source code and the errors please? It's difficult to suggest anything useful otherwise.

Do you both have the Uno selected as target device in the IDE?

Are you using the same version of the Arduino IDE.

I've had the same issue with Mac OSX 10.6.8 vs Windows XP SP3 using the same IDE version. I don't have a definitive answer for you, but I know that Microsoft has more frequent updates compared to Apple, which could be the reason. I suspect my issue and your friend's issue is the GCC compiler we're using. The compiler would be updated on OSX only when you update your entire OSX version. To get around that, there are third-party package managers: Homebrew and MacPorts that would allow you to just update the GCC compiler for example.


text:
Arduino Robot Chasis
I am looking into building a robot with my Arduino Nano but I don't want to shell out more then 50 bucks. Does anyone have any suggestions for a four wheel robot chassis at this price that I could use to make my robot mobile?

I'm voting to close this question as off-topic because we do not give out shopping advice.

There's plenty of options on ebay, you will have to add a DC motor driver and optionally, sensors, but these are a good starting point.

Depends on your definition of 'good'. The ones I have seen were not machined symmetrically, wheels rubbed the chassis, wires broke off the motor if you breathed on them. Just beware, cheap stuff is usually cheap stuff. Learning to properly cut and drill a $.50 piece of plywood is an as valuable skill as blinking an LED, maybe more.

I can only speak for my experience, which has been quite good so far.
A DIY approach works too, but generates lots of overhead.
Tools required to do a proper job usually do not come cheap.

The ones that are really cheap are from "Emgreat" ... simple and "good enough".  I'd suggest get a low end and play ... the model I bought can be seen here:
http://www.ebay.com/itm/Motor-New-Smart-Robot-Car-Chassis-Kit-Speed-Encoder-Battery-Box-For-Arduino-/361060892190?pt=LH_DefaultDomain_0&hash=item5410e7fe1e


text:
Arduino-controlled current limiter for lathe
I'm building a lathe that will be powered by a 3-phase 750w AC motor (4 pole, max unloaded RPM of 1400 RPM). I want to be able to control the RPM using a potentiometer attached to an Arduino mega which I can figure out how to do.
Under load, I'm guessing the motor is going to want to draw more current across each of the phases, the cabling can take the extra current draw but I don't want to damage the motor.
Could I use AnalogueRead (using current transducers) to tell the Arduino to increase the resistance with a servo-potentiometer setup or cut the power momentarily (using transistors on each phase) if the current rose above a certain level? If so, is there any code that would be good to steal/adapt?
Thanks all!


text:
Arduino TRE Release Date and Cost
I have been awaiting the release date for some time for the Arduino TRE.  So, my question is simple does anyone know the release date or any hints about when it might come out?  Also, what do you think the cost will be?

Who is making the TRE? LLC or SRL? All the throwing-toys-out-of-cots going on at the moment will most likely delay all new releases of hardware by at least 5 years.

Looking at the price of the Due, and comparing to BeagleBone or Raspberry Pi, I'm afraid it will be a lot more expensive than the latter two.

@Majenko: I didn't understand what you meant until now...good point! Thats sad. :-(


text:
Arduino DUE and a ledmatrix with issues
I am trying to code something for fun using an Arduino Due and a LED matrix. The led matrix has a backpack controller. This device is using SPI. So I connect MOSI and SCLK to their respective pins and SS to pin 10 on the Due. So far so good.
The problem I have is that when i run my rudimentary code nothing happens.
this is the current code I am using. I thought this should be enough, but it clearly isn't.
#include <SPI.h>
void setup() {
  SPI.begin(10);
  SPI.transfer(10, 0x26, SPI_CONTINUE); //setup the matrix
  for (int i = 0; i<64; i++){
    SPI.transfer(10, 0x00, SPI_CONTINUE); //set all pixels to black...
  }
}

Output:
 Erase flash
 Write 10444 bytes to flash
 [                              ] 0% (0/41 pages)
 [=======                       ] 24% (10/41 pages)
 [==============                ] 48% (20/41 pages)
 [=====================         ] 73% (30/41 pages)
 [============================= ] 97% (40/41 pages)
 [==============================] 100% (41/41 pages)
 Verify 10444 bytes of flash
 [                              ] 0% (0/41 pages)
 [=======                       ] 24% (10/41 pages)
 [==============                ] 48% (20/41 pages)
 [=====================         ] 73% (30/41 pages)
 [============================= ] 97% (40/41 pages)
 [==============================] 100% (41/41 pages)
 Verify successful
 Set boot flash true
 CPU reset.

So my question is: am I doing something wrong? what?
Or is the Led matrix broken?
Hoping for good answers.
regs
KB


text:
2 digit number to 2x 1 digit
Suppose I have a number with 2 digits, 42.
It is an integer, received from my RTC
Now for my 7 segment displays, I will need 2 separate numbers:

4 on display 1.
2 on display 2.

How do I slice this number in 2?

What is the type of the number? Is it currently stored as a string (e.g. char* or String) or is it an integer (e.g. int or byte or char)?

The OP mentions it is an integer.

Numbers retrieved from an rtc are usually returned as a char or integer.
On this basis, you want
ones_column = bytefromrtc % 10;
tens_column = (bytefromrtc / 10) % 10;
hundreds_column = (bytefromrtc / 100) % 10;

the % operator returns the modulus - if you divide 42 by 10, the answer is 4, with a remainder of 2. % returns the remainder, in this example, 2.
To do the tens column, first get rid of the last digit by dividing by 10, then do the modulus as above. Since bytefromrtc is not a float, if you divide it, you lose the remainder - 42 / 10 = 4, not 4.2.
If the output is a word, or integer, or long integer, the method is exactly the same, except for the number of digits you can get out.

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


text:
Multiple interrupt lines connection
In my project I need to connect more then 10 I2C sensors(MPU-6050) to Arduino Mega and an interrupt line for each sensor is essential.
Since the Arduino Mega only has several interrupt slots (digital 2, 3, 21,29,19,18), how can it be achieved? Is that using a multiplexer every time I switch sensors and also switching interrupt lines solve the problem?
The code I'm using is Jeff Rowberg's MPU-6050 DMP example, which means interrupt line is essential and important, also very sensitive (a wrong change can cause sudden stop)..
// 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 Arduino
    // 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);
    }
}

possible duplicate of Why is that any sensor signal need to be hooked up to the interrupt pins on Andruino boards?

One possible solution is to use a "global" interrupt pin which all the sensors use, and also normal GPIO pins to work out which interrupt has occurred.
Feed the interrupt signals into a multiple-input OR gate (if they are active HIGH) or a multuple-input AND gate (if they are active LOW).  The output of that AND gate goes to a single INT pin.  Each interrupt signal also goes to a normal IO pin.  When the interrupt pin triggers the ISR can then look at the IO pins to determine which of the interrupt signals that triggered the interrupt.

For fastest operation use IO pins that are on the same port and use direct register reading for that port to see which bits are on and which are off.

This has little-to-no difference versus pin change interrupts other than using up an external interrupt.

You can also use four regular diodes instead of an or port.

Good possible solution. remember to use digitalReadFast (or write the code yourself), instead of 10 Arduino's slow digitalRead. You probably get all the information you want from 2 reads.

@Ignacio PC ints are slower

to clarify, the answer is a good possible solution, not Pin Change interrupts.

Thanks @Majenko it's sound an awesome solution , I'm kind of under stand what you trying to do but since I didn't have much electronics background I would like to ask few questions further : 1) in my understanding ,IRQ0-3 have been connect to Arduino's normal digital pin, IO0-3 have been connect to different MPU6050's INT pin, and IRQ is been connect to Arduino's single interrupt PIN; ,2) IRQ0-3 is support for 4 devices , if I want trigger IO0 then I feed 1000 to this array ;at mean time it trigger's selected device it will also trigger Arduino's INT pin

I cannot just feed one IRQ signal but leave other empty (like 1---) I must assign one of the pin with HIGH but leave others LOW

The arrangement I show uses active-low interrupts, which are normally HIGH and go LOW when triggered.  They come in from the MPUs on IRQ0-IRQ9 (if you expand that to have 10 inputs).  If the interrupts are active HIGH (normally LOW and go HIGH when triggered) then you need to replace the AND gate with an OR gate.

@Gerben: I'm new to electronics, can you give a link on how to use diodes to do this?

@MichelKeijzers Zie http://www.slottechforum.com/slotinfo/Techstuff/CD2%20Diodes%20and%20Transistors/Diodes/06030101F%20diode%20OR%20gate.jpg

@Gerben dankje!

Just FYI, the interrupt is not essential. If you can write efficient code you can read an MPU(DMP) without it (UNO, been there, done that). But that is only for one MPU. I doubt if an UNO can keep up with 10, no idea about the faster processors. In any case, even with interrupts, I doubt if an UNO could keep up with 10. Keep googling and you will find a note how to change the sampling rate to slow the MPU down.
The code you referenced provides AHRS (Attitude Heading Reference System) - I would be real curious to see what projects needs 10 of those :) Sounds like fun.

I'm actually computer science students , currently doing research on medication area by using machine learning algorithms :)

unfortunately , I firstly tried using without interruption however, because of the behaviour of this MPU,  without interruption will make the MPU 'unstable' , the FIFO cannot consume as I wanted , after several minutes MPU start oscillating and crazy. I have spend lots of hours on that but still , makes me lots of headache :) so I will still looking for the interrupting solution , but many thanks for your support !

keep trying, like I said, I know it works :)  One thing to do is clear the FIFO buffer every read (same as it does in case of an overflow).  Since you are just reading, there is no requirement for your code to integrate, so even if your losing some data, it doesnt matter.

shameless plug - keep an eye on spiked3.com - video demo coming soon with MPU-6050 and others on a UNO. I am finishing up some other parts of the code now, but that part is finished and working incredibly well. I'll try to put a preliminary demo video up later tonight.

Is it??  I know I need to clear MPU buffer but I've tried every reset function listed in the library however it does not work , could you give me more details please I will be so pleased to see it !

Hi I've just post a new form about this specific question link


text:
Stuck in a small confusion about Infrared leds and receivers?
I have a very simple idea I want to implement. I am making a home automation using an Arduino Uno. I am familiar with Arduino programming but the problem is what kind of IR receiver I need to buy if i want my TV remote (or similar) to communicate with my Arduino.
Can you suggest me any example (low cost, and available in India)?

Your title says "LED", but your body says "receiver".

Aren't they same

LEDs transmits IR light. Receivers receive the (modulated) IR light. You can get IR-receivers from old VCR etc.

Element14 has an India based store, and they carry these IR devices.
Here is one for 66 rupees:
http://in.element14.com/vishay-semiconductor/tsop38238/ir-receiver-45m-38khz-th/dp/2395954?MER=MER-BPR-4PPM-SP-VSHY-OD&
You may want to do research into what the carrier frequency of your remote is also. Most are generally around 35 - 40khz, and the receiver I provided a link to is 38khz. It should work, but if you want to be safe I suggest you look it up. Or, if you have an old TV lying around, you can pull one out of that.
Hope this helps.


text:
Unexpected Timer Conflicts (Uno)
I've been working on a project (Arduino Uno: Atmega328) that implements a gyroscope (which is used with the LSM9DS0 spark-fun library) that is communicated with through I2C and uses a Servo library. Due to a timer conflict with the standard Servo library and another library I've been using, I am now using the ServoTimer2 library which obviously uses timer 2. This is when the problem started.
When I call the attach() function of the ServoTimer2 library, it allows the gyroscope to be read a few times and then the gyroscope feed cuts out. I am using the serial monitor (115200 baud) to read the gyroscope data. The Serial monitor is not the problem because it uses a UART interrupt for Serial.
To fix this error, I modified the ServoTimer2 library to run on Timer0 (Yes I know this handles the delay functions, but they are not needed in my case), which is now called ServoTimer0. This modified version of the library works perfect except for when I attempt to use it with the gyroscope. The same problem still arises though. I've traced what causes this failure down to one line of code that sets up the interrupts:
TIMSK0 =  _BV(OCIE0A) //This is in my own modified version of the library.

That is what causes it to fail. I believe the AtMega328 can run I2C natively, and my thought is that this native running somehow uses these timers.
Any solutions?
Thanks

The I2C (Wire) functionality does not user Timer0. TIMSK0 = _BV(OCIE0A) //This is in my own modified version of the library.: That line enables the output-compare interrupt. Why are you enabling that? Do you have a handler to handle that interrupt? That would look like this: ISR(TIMER0_COMPA_vect) { // some code }

Please post your code. The line you mention needs the TIMER0_COMPA_vect interrupt vector to be supplied or it will crash.


text:
Need a simple accelerometer visualization example!
I'm doing a project using the ADXL335 accelerometer from SparkFun. The actual project I'm using P5 and it's working great. I'm running workshops in parallel and want to demo the chip in real-time but am currently out of time to build something from scratch. I'm desperate for a simple processing (or something else) sketch that takes my x, y, z values being printed to the serial port from Arduino and visualizes them in some way. Can anyone point me to anything that won't need a lot of coding time and effort just now?
Thank you!
Claudia

After some quick searching I found an Instructable which uses your same sensor and plots the data thanks to a Python script. You'll need to install Python if you want to replicate this project, but any programming language with a drawing library will work.

https://learn.adafruit.com/ahrs-for-adafruits-9-dof-10-dof-breakout/visualizing-data

Here's my Python implementation.
It's desined for AOK-D but can be easily converted to work with external sensor
IMU+AHRS

A simple and fast solution would be implement a chart using a JavaScript library called Chart.js. it is simple and you can visualize your data in realtime.
Try node.js to make the back-end by communicating via serial (serialport package is good) and send the data using socket.io.
It is simple and you can set everything in less than 2 hours.
Chart.js
I recently made some video tutorials about this and you see them here. The audio is in Portuguese but you can just skip and go directly to coding sections.

All great answers - thanks for each of them!! A processing forum user provided me with a processing script that worked great for my purposes. You can view the thread here:http://forum.processing.org/two/discussion/comment/40648


text:
Coding for Seeed Arduino motor shield
I acquired a Seeed studio Arduino motor shield V.2 and wanted to start using it. The problem is that there is like no good example code. The library for the shield on the seeed website has one example and doesn't really explain anything. Does anybody know where I could get a good guide for this thing?

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


text:
Proportional water flow control
I've been looking at water flow control with Arduino and I'm finding a huge difficulty in managing to do an 'analog' control on water flow. The mainstream solution seems to be the well known solenoid valve, however those seem to be binary (full flow, no flow), and I'm looking for a more variable answer.
Is it possible to get middlegrounds with solenoids? Maybe actuating them with less voltage or amperage will cause it to partially actuate? If not, does anyone know of embedded solutions using servos or steppers maybe?

Only thing that comes to mind is multiple solenoids, which is probably not what you are looking for.

why not just control the pump speed to control flow thats what I do.

Because there is no pump. This is connected to a pressurized water pipe.

Is it possible to get middle grounds with solenoids?

No.  The solenoid will be all or nothing.  If you have used a magnet, you have seen that the force decreases rapidly with distance.  As you move something closer, it will typically snap to a magnet at one point.  The same thing happens in a solenoid valve: once you apply enough voltage to start motion, the motion will complete.
Side note: that is actually a common trick to saving much power with solenoid valve.  You might apply 12 V to actuate, but then you can reduce the voltage very low (maybe 2 V or lower) and the valve will still say actuated.
So if you want flow, you need a flow control valve.  A common 1/4 turn ball valve will provide the fractional flow you seek.  You should be able to hook a servo or gear motor to that.
A typical ball valve will not provide a constant change of flow with angle.  That means the change in flow between the first 5 degrees opening will be large while the last 5 degrees of motion will have little effect.  If the application is not critical, that would be fine.
If you want more precise flow control, valves are made with a particular cutout in the ball that makes the flow control more linear.  You can get a commercial type valve with motor attached in cost range of 100 $US.  For hooking up to an Arduino, a Belimo flow valve (one example vendor) only seems appropriately named

These are commercial type valves used to control water in heater systems and such.  They take a 0 - 10 V input signal as control and will rotate the vale.  The keyword search is "motorized flow control valve" and that will find you many.  These are not exotic, you will find many in all sorts of sizes.  You may even find from a local plumbing supplier where you can pick one up at will call.

Do you use a pump to circulate the water flow, if so maybe you have a better result with a variable pump speed (PWM), in state of a variable valve opening.


text:
The code of ISR executes twice
i am using Arduino Mega.. ANd this is the code:
void bump(void);

void setup()
{
    pinMode(19,INPUT);
    attachInterrupt(4,bump,HIGH);
    pinMode(13,OUTPUT);
}

void loop()
{

}

void bump()
{
   for(float i = 0; i < 90000; i++){
   digitalWrite(13,HIGH);
   }
   for(float i = 0; i < 10000; i++){
   digitalWrite(13,LOW);
   }

}

Although i give +5 V to it once, the LED will blink twice...!
What is the solution?

Why have you chosen float as the data type of your counter, 'i'? At least, is 'float' used elsewhere in your program? If not, this use drags in a lot of code, just for counting. And why are you re-writing your port i/o on each count? Wouldn't: digitalWrite(13,HIGH); delay(ONTIME); digitalWrite(13,LOW); delay(OFF_TIME); do what you intend?

@JRobert: I wanted a huge value for i so i chose float.. Mayb long would have been better.. And we can't use delay inside ISR..

ISRs should never do more then needed. You can block other functions of the Arduino. Very seldom do I do anything more then set or clear a flag. In some variations of the Arduino family long times will cause it to crash.

After wondering over it for quite a long time, I finally came to the conclusion, that the interrupt should be made to trigger at RISING edge, if I want it to go into ISR the moment it gets HIGH.
Hence the setup line was change to
attachInterrupt(4,bump,RISING);

And the cod e works well.
I suppose that is because, when it receives a HIGH signal, than the period for which it receives HIGH is a bit long, during which it adds another interrupt into the queue, and so the ISR is executed once again.

Remember to mark your answer as solution in three days ;)

Oh yes, thanks a lot.. I didn't knew that :)


text:
Is it harmful to write to unused bits in PORT registers?
Background:
I'm looking at writing a library to drive an LED matrix panel (one of these:http://www.adafruit.com/product/607) from my newly acquired Arduino Due.  My background is C++ programming, not electronics.
I'm planning to experiment with various optimisations of the code for memory and speed, but one constant is that I would like to be able to send the data to the matrix with single memory writes to port registers without having to use masking operations to leave certain bits unaffected.  As I need to send 6 bits of data with a clock signal, I figured this could be easy with an 8 bit write to one byte of a port register.  The 8th bit/pin could be used as the latch or some other used line.
Looking at the nice pinout diagram that someone has kindly put together (http://forum.arduino.cc/index.php/topic,132130.0.html), I was pretty shocked to discover that my plans weren't going to be as easy as I would have liked.  There are only two circumstances where there are whole bytes of port registers that connect to digital pins (Port A byte 1 and Port D byte 0).  All other bytes have "holes" in them, for example Port C byte 0 has no connection for bit 0, but has bits 1-7;
While two complete bytes is enough (I actually only need to use 13 pins to control the display, plus ground connections), the pins of the available two are spread out in a way that would make it a little awkward for me to make a stripboard shield as I intended due to the pins on the Arduino boards not being evenly spaced (why is that?) and I'm guessing that since most of the digital pins in Port A byte 1 are used for communication pins (including RX0 and TX0) I would lose my ability to print to the debug log.  As a result, I've ruled out using those port registers.
That leaves me with bytes 0 and 1 of Port C.  There are just enough pins available with those bytes and they are grouped nicely on the double connector at the bottom of the board (Digital pins 33-40 and 48-51), however some bits in those bytes are not mapped to Arduino IO pins.
Would it be bad if I were to write to bits of a port register that do not have Arduino IO pins assigned to them?  Would the answer depend on whether I had set those bits to be inputs or outputs using the Output Write Enable Registers?  I'm assuming that these bits are used for IO pins on the SAM3X8E chip but just not made available to the Arduino boards.

If the pins have no connection to the outside world (i.e., they don't have any actual pin associated with them on the SAM3X chip) then writing to the PORT (or indeed any other register associated with them) will have no effect whatsoever.
If they have a pin but that pin is not connected to anything, then there will be little effect.  There may be slightly increase current draw as the pin switches on/off, or you enable/disable the internal pullup resistor, but that's all.
If the pin exists and is connected to something on the board - maybe a button or LED, then you will basically be providing an output to that item.  If it's an LED it will flash.  However, if it's a button, and you provide an output opposite of its active state (i.e., provide a HIGH when it normally connects to ground when you press it) and that button lacks any current limiting resistance, then you could risk burning out that IO pin if the button gets pressed.
If the pin just goes straight to a header, then as long as nothing gets connected to that header then there will be no effect other than as detailed in the "pin present on the chip but not connected".

Thanks for the very concise info. Do you known how I can find out if the bits of a PORT register do relate to pins on the SAM3X chip and then if those pins are used on the Arduino board?

Read the datasheet and the schematic.


text:
send SMS for 1 time with arduino GPRS SIM900 if an iput is HIGH (4 Digi inputs)
I faced a problem to send 1 SMS if an input is HIGH,and if it is LOW==> no SMS to send,if LOW to HIGH==> send 1 SMS. this code not working,just sent SMS when I turn the GPRS on,and after nothing is happened.
Thank you for helping in advance.
 #include <SoftwareSerial.h>
 #include "TimerOne.h"

 const int DI = 2;
 const int DT = 3;
 const int DGP1 = 4;
 const int DGP2 = 5;
 const long interval = 100000; // in microseconds

 int value1 = 0;
 int value2 = 0;
 int value3 = 0;
 int value4 = 0;

 int value1_old = 0;
 int value2_old = 0;
 int value3_old = 0;
 int value4_old = 0;

 boolean changed1 = false;
 boolean changed2 = false;
 boolean changed3 = false;
 boolean changed4 = false;

 SoftwareSerial SIM900 (7, 8);

 void SIM900power(){
   digitalWrite(9, HIGH);
   delay(1000);
   digitalWrite(9, LOW);
   delay(5000);
 }

 void initia(){
   SIM900.print("AT+CMGF=1\r");
   delay(100);
   SIM900.println("AT + CMGS = \"xxxxxxxxxx\"");
   delay(100);
  }

 void Send_SMS(){
    SIM900.println((char)26);
    delay(100);
    SIM900.println();
    delay(5000);

  }

  void isr_timer(){
    if (changed2) {
      initia();
      SIM900.println("Station 85: Defaut electrique");
      delay(100);
      Send_SMS();
      value2_old = value2;
      changed2 = false;
   }

   if (changed3) {
     initia();
     SIM900.println("Station 85: DefautGP1");
     delay(100);
     Send_SMS();
     value3_old = value3;
     changed3 = false;
   }

   if (changed4) {
     initia();
     SIM900.println("Station 85:DD>1000");
     delay(100);
     Send_SMS();
     value4_old = value4;
     changed4 = false;
   }
 }

 void setup() {
    pinMode(DI, INPUT);
    pinMode(DT, INPUT);
    pinMode(DGP1, INPUT);
    pinMode(DGP2, INPUT);

    SIM900.begin(19200);
    Timer1.initialize(interval);
    Timer1.attachInterrupt(isr_timer);
  }

  void loop() {
    value1 = digitalRead (DI);
    value2 = digitalRead (DT);
    value3 = digitalRead (DGP1);
    value4 = digitalRead (DGP2);

    if (value1 != value1_old && value1 == HIGH) changed1 = true;
    if (value2 != value2_old && value2 == HIGH) changed2 = true;
    if (value3 != value3_old && value3 == HIGH) changed3 = true;
    if (value4 != value4_old && value4 == HIGH) changed4 = true;

    value1_old = value1;
    value2_old = value2;
    value3_old = value3;
    value4_old = value4;

  }


text:
Multiplexing help for relay and pwm
I have to control with an Arduino UNO and xbee shield:

9 5V relay
9 RGB LED

What kind of multiplexing can you advice me? Do I have to use external power supply (like 12V DC external from arduino or from vcc)? Is there any kind of already ready-to-use shield?
EDIT
I'm planning to use a 8 relays shield plus one single relay

You can use shift registers to control the relays. This will only use 3 pins and allow you to use the xbee.
For the RGB LEDs you can use the TLC5940 to control 16 channels, so you will need two, giving you 32 channels. This is a PWM chip with serial interface.
Considering you will be using the board linked. It is driven by transistors, so you can use the shift registers.
For the power supply, if you will be operating all of the relays at the same time it will draw about 650 mA (9x72mA), you will need a separate 5V power supply for the relay board, as I believe drawing that much current will heat the board and regulator a lot. If one at a time it will not draw too much, so its possible you can run it all off the Arduino.
A forum post of someone running 360 relays with shift registers.

all of the relay can be on all time, and also the led

@nkint - definitely get a separate power supply. A power supply that can give 5V 1A should be sufficient


text:
How can I best control various high power LEDs without using PWM
I want to be able to dim various high powered (20mA) LEDs in an array (8X12 LEDs). I do not need individual control, but would like to be able to dim each row (or two rows together) so that I can create gradients.
An important caveat is that I can't use pulse width modulation (PWM) as there should be no flashing whatsoever, even if it is invisible to humans.
How can I best achieve this?
(I do not care about energy efficiency)
The fist thing I found which seemed to be the right solution in the beginning is using digital potentiometers as explained in this tutorial. However they only support low currents so I can't use one channel for 8 or 16 LEDs.
Maybe I could use various digipots in parallel with one Arduino, each powering 1 LED per channel? But that sounds overcomplicated and a nightmare to wire up. Is there a more elegant solution?

It might support low currents, but that shouldn't mean you couldn't use the output as input into a transistor.

Better ask at http://electronics.stackexchange.com/ . Also, how have you wired the matrix? More specifically, how do you power it? I'd probably create a constant current circuit, and use the digital pot to set the current.

The figure below illustrates a method of current control.  It shows four LEDs in a 2x2 arrangement; one  would adapt the number of LEDs in series or parallel in accord with how one's array is wired, what voltages are available, LED current requirements, transistor power limitations, etc. [Edit: See transistor-power example calculation at end.]
Each separately-controlled group of LEDs would need one such circuit.  Each circuit needs one control voltage (eg, from a DAC or a digital potentiometer voltage divider circuit) and needs one transistor per series chain.

Circuit Operation:
Suppose the following conditions hold.

Q1 and Q2 are equivalent transistors and Vbe is 0.7 V typ. (one diode drop)
D1, D2, D3, D4 are equivalent LEDs
Resistors R1, R2 are small and equal (eg 1–30Ω)
V1 is some fixed DC voltage, eg about 1 V
V > 2*Vf + Vbe + VR where Vf = typical forward voltage of D1...4

Under these conditions, V1 will drive current into the bases of Q1 and Q2, causing transistor-amplified current to flow through R1 and R2 and maintain the condition V1 = Vbe + VR1 = Vbe + VR2.
Here is a concrete example:  Suppose we want 23 mA through each LED and that R1=R2=17Ω. VR = IR = 0.023 mA · 17 Ω = 0.391 V.  If Vbe is about 0.7 V, then we set V1 = 0.7 + 0.391 V or about 1.09 V to get 23 mA through each LED.  More generally, to get current I through the LEDs we solve V1 = Vbe + VR = 0.7 + IR = 0.7 + I·17.
Base current:
The amount of current required from the V1 voltage source depends on transistor hFE or β.
Eg, if β is about 100 and ILED is 20 mA then each transistor will need about 20/100 mA or about 200 μA of base drive.  This amount of current probably could be delivered by a voltage divider based on an AD5206 (the digital potentiometer chip that's used in the SPIDigitalPot tutorial mentioned in the question).
Power Dissipation:
The AD5206 digital potentiometer datasheet shows an absolute maximum rating for Package Power Dissipation of  (TJMAX-TA)/θJA.  If ambient TA is 25℃ and θJA is 70°C/W (as for a SOIC package) this gives (150-25)/70 = 1.8 W max package power.  However, it would be reasonable to limit dissipation to under half a watt.  In the 10 KΩ version of the AD5206, that means a little less than 2.9 mA maximum per channel.  [I = √(0.5 W /(6 channels * 10000Ω)).]  If several low-beta transistors are used to drive several strings of LEDs, 2.8 mA might be marginal.
Voltage-divider Linearity:
Only a small fraction of the current through a voltage divider can be drawn off without upsetting the division ratio.  A unity gain buffer amplifier [as in the following figure] can be used to increase linearity of voltage-divider output by providing a high-impedance connection to the divider.

(In the figure above, R1 and R2 are not related to R1 and R2 of the previous figure.  Here, R2 represents a digitally-variable resistor.  Choose R1 and R3 so that V1's range is from slightly below Vbe to slightly above  Vbe + ImaxR, where Imax is the maximum LED current desired.  For example: Suppose V=5 V, that R2's total resistance is 10 KΩ, that R is 15Ω, that Vbe is 0.7 V, and Imax is 25 mA.  Let RT = R1+R2+R3.  Now R3/RT = Vbe/V = 0.7/5 = 0.14, and R1/RT = (V - Vbe - ImaxR)/V = (5 - 0.7 - 0.025·15)/5 = 3.925/5 = 0.785.  Thus R1+R3 = 0.925·RT, whence 0.075·RT = R2 = 10 KΩ, giving RT = 133 KΩ, R1 = 105 KΩ, and R3 = 19 KΩ.  With these R1 and R2 values, each digital pot step should give a change in LED current of 25/256 mA, or about 98 μA.)
[Edit:  When V1 is set to less than VBE, no current will flow through the LEDs.  That is, to turn off the controlled LEDs, set V1 to VBE or less.]
PWM with RC filter:
It may be worthwhile to experiment with using a PWM-driven low pass RC filter to supply V1, possibly avoiding need for buffer amplifiers and digital potentiometers.  See eg “Arduino’s AnalogWrite – Converting PWM to a Voltage”
by Scott Daniels at provideyourown.com, and also see the filter-calculation page it refers to.  You might need an oscilloscope to verify the design and its quality of results, and might need to use several RC filter stages in a row to adequately filter out ripple, but it can be done, at the cost of slower response to control changes.
Transistor-power example calculations:
Letting  VCE, ICE, VBE, and IBE represent collector-to-emitter and base-to-emitter voltages and currents, transistor power dissipation is VCE·ICE+VBE·IBE.  Because VBE·IBE is likely to be sub-milliwatt, we ignore it in following, taking P ≅ VCE·ICE.
In the LED-driving circuit,  VCE = V – VLEDs – Vsense, where VLEDs is the series voltage across the chain of LEDs the transistor controls, and Vsense is the voltage across the sense resistor (ie, across R1 or R2 in the top figure).
In general, it is a good idea to keep Vsense small (under a volt) to allow a wider compliance range – ie, so that LED current is the same over a wider range of variation of supply voltage V.  Thus, the approximation  VCE ≅ V – VLEDs is reasonable.
Here is a concrete example: Suppose we have eight LEDs in series, and they are white LEDs with about 3.6 V forward drop at 20 mA. [LEDs of different colors may have different drops; eg see LED color chart at oksolar.com.]  Then VLEDs = 8·3.6 V = 28.8 V. We need V(BR)CEO > V > VLEDs + VBE + Vsense, where  V(BR)CEO = collector-emitter breakdown voltage (which is 40 V min. for 2N3904 or 2N2222).  Allowing a volt for Vsense and 0.7 V for VBE we have V > 28.8 + 0.7 + 1 = 30.5 V.  Let's suppose V=32 V.  Then P < (32–28.8)·0.020 W = 64 mW.  Thus a small general purpose NPN transistor will work, for example a 2N3904 (rated at 350 mW to 1 W, depending on package, before derating for ambient and heatsinking) or a 2N2222 (similarly rated).
For a second example, suppose VLEDs = 8·1.7 V = 13.6 V (for, eg, eight infrared LEDs at 50 mA) and V=32 V.  Then P ≅  (32–13.6)·0.050 W = 920 mW, so a larger (and heatsinked) transistor would be needed.  Or, V could be decreased, say to 16 V, giving  P ≅  (16–13.6)·0.050 W = 120 mW, allowing use of a small transistor.
For a third example, suppose eight LEDs are paralleled (rather than seriesed), that VLEDs = 2.0 V at 20 mA, that Vsense is about 0.4 V at desired operating point, and that V=5 V.  The transistor will need to drop 5-2-0.4 V = 2.6 V at 160 mA, which is 416 mW, probably large enough to require a heatsink.  [Note:  if LEDs are placed in parallel and driven by a single transistor, some of them probably will be dimmer than others; “current hogging” may occur in some of the LEDs, making them brighter than the others.  However, many cheap flashlights connect LEDs in parallel without individual current control.]

Thank you very much for your response!
Please bear with me, I am far from an electrical engineer.
If I understood you correctly, the basic idea is to use transistors (Q) to create the dynamic resistance for the LEDs. The resistance of the transistors in turn is controlled through the digipot (V1).
How many LEDs could I wire to a single transistor without burning it? Ideally I would like to wire 8 LEDS (one row) per transistor. Is there a specific transistor you would recommend? I guess I need high max resistance to be able to dim the LEDs to almost off.

(1) Re “How many LEDs”,  see example power calcs, added at end.  (2) Re  “high max resistance” for dimming, see added note: “When V1 is set to less than VBE, no current will flow through the LEDs”.  Ie, low V1 voltage turns LEDs off, rather than a large resistor doing so.


text:
Nano destroyed?
Board: OE Gravitech Nano
Is it possible to destroy the board if there are a voltage on a Analog pin while the board is not powered?
I have a application that use a analog (speed) voltage 0-4,9 from a GPS module, this worked very nice for a hour of 10, after that the voltage seems to be not constant available.
Maybe the user have powered off the Arduino while driving the machine.
Regards,
Rien

Assuming you're talking about the device with this schematic (or similar), the "analog" pins go directly to Atmel AVR I/O pins with no series resistance, so yes, it's quite possible to damage the microcontroller. Add some series resistance of a few K and you'll have a better chance of the part surviving such an event.
The voltage on any pin should not, under any circumstances exceed Vcc+ 0.5V as the datasheet specifies, however it's usually okay under non-operational conditions if the current is limited to much less than the 40mA. A 4.7K resistor would limit the current to less than 1mA with a 5V input.

So if I understand this correct, if VCC are 0 (Arduino not powerd)a signal higher then 0.5V on a Analog input pin destroy the Arduino?

Sort of. I'm going to a be a bit persnickety about this. It says that if you keep the voltage less than 0.5V with Vcc = 0 you will not destroy the Arduino immediately. In fact you can exceed that voltage if the current is limited (series resistor) without immediately destroying the chip (the voltage might go up to 0.7V or 1V with a few mA flowing). Nothing is said about proper operation under these type of circumstances. The data sheet does not say this explicitly, but if you put several volts on the input with Vcc held to 0V, you will destroy the chip.


text:
How to clear FIFO buffer on MPU6050?
my MPU6050 works very unstable , the problem is unable clear excessed FIFO buffer on MPU6050, I am using Jeff Rowberg's MPU library and according to his DMP example but without using interruptions,here is my modified code but I've tried several method listed in the library to clear buffer but doesn't work..
Thanks very much!
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "Wire.h"

MPU6050 mpu(0x69); //AD0=High

//MPU control/status vars
bool dmpReady = false;
uint8_t mpuIntStatus;  //actual interrupt status byte
uint8_t deviceStatus; //device status , 0 = success ,
uint16_t packetSize; //expected DMP packet size (defult 42) -- ?
uint16_t fifoCount; //count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO buffer storage

// 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

volatile bool mpuInterrupt = false;
//void dmpDataReady() {
//  mpuInterrupt = true;
//}

// put your setup code here, to run once:
void setup() {
  //join I2C bus
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 48; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif
  //initialize serial communication
  Serial.begin(115200);
  while(!Serial); //common for Leonardo issues

  //initialize the mpu
  Serial.println("Call MPU6050 Lib to initialize devices...");
  mpu.initialize(); //initialize I2C device by using MPU6050 library

  //verify connection
  Serial.println("Tesing device connections");
  Serial.println(mpu.testConnection() ? F("MPU6050 connection test successed ") : F("MPU6050 connection test failed"));

//  //wait for begin , uncomment if we need wait user interruption
//  Serial.println("Press any button to begin");
//  while (Serial.available() && Serial.read()); // empty buffer
//  while (!Serial.available());                 // wait for data
//  while (Serial.available() && Serial.read()); // empty buffer again

  //load and configure DMP
  Serial.println("initializing DMP");
  deviceStatus = mpu.dmpInitialize(); //use MPU6050 library to inilisalize the dmp

 //feed offsets
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

  //make sure it works
  if (deviceStatus == 0) {
    Serial.println("DMP initialization success, now enable DMP for use");
    //turn on DMP
    mpu.setDMPEnabled(true); //use MPU6050 library to enable DMP)

    //wait for first interrup . currently just leave it false automatically
    mpuInterrupt == false;

    //let main llop know it's ok to use DMP, set dmpRead flag to ture
    dmpReady = true;
    Serial.println("DMP is ready to use.");

    //get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    //ERROR! , device status !=0 when initializing DMP
    Serial.print("DMP initialization failed when using MPU6050 library:");
    if (deviceStatus == 1) {
      Serial.println(" intial memory load failed");
    } else if (deviceStatus == 2) {
      Serial.println(" failed to update DMP configuration");
    } else {
      Serial.print(" unknow error with code: ");
      Serial.println(deviceStatus);
    }
}
}

int ticket = 1;
void printOnlyOnce (String message){
  if (ticket == 1){
   Serial.println(message);
   ticket = 0 ;
  } else {
    return;
  }
}

void loop() {
  //if DMP not ready don't do anything
  if (!dmpReady) {
    printOnlyOnce("MAIN LOOP: DMP disabled");
    return;
  } else {

    //testing overflow
    if (fifoCount == 1024) {
      mpu.resetFIFO();
      Serial.println("FIFO overflow");
    } else {

    //wait for enough avaliable data length
    while (fifoCount < packetSize) {
      //waiting until get enough
      fifoCount = mpu.getFIFOCount();
    }

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

    //track FIFO count here is more then one packeage avalible

    //reset fifo count
    fifoCount -= packetSize ;
    Serial.println(fifoCount);

    if (fifoCount > 2) {
        ////// clear fifo buffer
    }
    //display stage
                // 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);
  }
  }
}

How do you know that the FIFO buffer is your problem?

hi , because I've tested it :)

But what method of testing did you do that isolated the problem to that buffer?

By eliminating other potential problem sources one by one to this one , it took me about 8 hours :)

Yank,
I ended up clearing the buffer after every read.  In your code it would be following the line
//read this packet from FIFO buffer
mpu.getFIFOBytes(fifoBuffer,packetSize);

I added
mpu.resetFIFO();

I came to this conclusion after watching when the over flows occurred. The fifo buffer is adding on to the end of the buffer, and when it gets full, rather than wrap, it over flows. Reading does not seem to remove data from buffer in any way.  By clearing the buffer you might be discarding data, but the DMP is doing the integration for AHRS for you, so you really do not need to worry about dropping data since you are only interested in the current pitch,roll,yaw or Euler or whatever, at least that was my case.
I am running it on an Arduino UNO shield prototype and it is rock solid stable (at the default 100 hz rate). See spiked3.com PiPlate / Pilot.

Thanks Spiked3! I'm currently hard testing it , in my situation I need use history data from 12 sensor's reading and 100% stable running for at least 10mins and feed into my machine learning algorithm,and I know even if I use interruptions ,  I think you enlighten my life ! I will give my testing results this afternoon and approve it ! :)

After testing with different frequencies and hours , the sensor remain stable without any faulty data! Thanks @Spike3

Leave comment on the other question as well, that this worked.

What if we can increase the size of the FIFo Buffer.
uint8_t fifoBuffer[64]; // FIFO storage buffer

What if I change it to lets say:
uint8_t fifoBuffer[1024]; // FIFO storage buffer

and then change :
if ((mpuIntStatus & 0x10) || fifoCount == 16384) { // I changed 1024 -> 16384
    // reset so we can continue cleanly
    mpu.resetFIFO(); // Resets the FIFO buffer when set to 1 while FIFO_EN equals 0.
    Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
}

Please check these changes.

To prevent overflow problems, please, go to MPU6050_6Axis_MotionApps20.h and modify that line:
0x02,   0x16,   0x02,   0x00, **0x01**                // D_0_22 inv_set_fifo_rate

The value in bold is the objective! Change it to 0x03 or 0x04 or 0x05 to reduce the Hz of rate. I am using 0x03 and not getting error values, junk data, or overflows anymore.

I know I had tried this in the past (it is what a simple google turns up), but I thought I would try it again to be sure since you posted it a month after my accepted answer. Same results as before, nothing but overflows. All it does is slow down the overflows, it does nothing to eliminate them.

Actually when I tried this it even gave me bad results. The values I read were just scraped. Can't down-vote here but this is a bad approach!


text:
Activate a DC motor for a fixed amount of time
I have a single simple DC motor that upon a condition I wish to let it run for 3 minute. How can I do it in Arduino? a simple addition to the code will be great help.
As I use Adafruit motor shield this is my current code:
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
IOvalue = 1000

if (IOvalue = 1000) {

 //this is the motor I wish to run for 3 min
   myMotor->setSpeed(25);
   myMotor->run(FORWARD);
   delay(100);
 }
}

Thanks a lot

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
boolean motorRunning = false;
unsigned long motorStartMillis;
unsigned long motorRunMillis = 180000;

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
  IOvalue = 1000

  if (IOvalue = 1000) {
    //this is the motor I wish to run for 3 min
    myMotor->setSpeed(25);
    myMotor->run(FORWARD);
    motorStartMillis = millis();
    motorRunning = true;
  }

  // check if motor is running and time-to-run has elapsed
  if( motorRunning && (millis()-motorStartMillis > motorRunMillis) )
  {
    myMotor->setSpeed(0);
    myMotor->run(RELEASE);
    motorRunning = false;
  }
}

long int currentMillis;
void setup() {
    pinMode(motorPin, OUTPUT);
    digitalWrite(motorPin, LOW);
}
void loop() {
    if(condition is met){
        startOfMotor = millis();
        while(millis() != (startOfMotor+180000)){
            digitalWrite(motorPin, HIGH);
        }
    digitalWrite(motorPin, LOW);
    }
}

This motorPin is the pin to which the motor is connected. millis() gets the milliseconds after the board is started. 3 min = 180 seconds = 180000 ms.

Thanks. I forgot to mention that I use Adafruit motor shield and therefore how can I integrate you code into this snippet.
Code:
void loop() {
…..
….
if (IOvalue = 1000) {
//this is the motor I wish to run for 3 min
myMotor->setSpeed(25);
myMotor->run(FORWARD);
delay(100);
}
}

Can you edit your question to show the code? It is hard to read it in comments.

About the shield.. I need to know more about your setup.

Updated the question and embedded the code.

I have no idea about the Adafruit motor shield. Sorry! (For such simple operations you are better off using the Arduino itself. )


text:
Making my own libraries
Does anyone know of a site or book where you can learn how to create, or for first reed, libraries. Because I think the libraries I use are sometimes unnecessary complicated, or have similar features, for example Wire and OneWire.
I think, these make my sketch unnecessary big, when I need both of them.

Wire and one wire are two different things. If you are looking for arduino libraries, there are tutorials on how to make your own on the arduino site, sparkfun might have something and I might be wrong here, but Arduino cookbook, might have.

Just look at the source code of a few libraries. That's the advantage of open-source.

http://www.arduino.cc/en/Reference/APIStyleGuide  -  http://www.cplusplus.com/

Arduino has a library tutorial here: http://www.arduino.cc/en/Hacking/LibraryTutorial
and a formal specification here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification
these explain the specifics to making arduino libraries, like the propeties files, the keywords file, and the directory structure. Most of that is unnecessary though.
Anyway, there are not many differences between the actual code in an arduino library and the normal code you write for arduino sktech. The only major ones being that

The arduino preprocessor doesn't generate function declarations - you have to make your own header file
You can't use setup or loop

Other than that, its just normal c++ code that exposes a particular interface and provides an implementation. If you want the library to work well for a lot of users, you will need to put in the extra work to make it run on all the different arduino hardware variants.
Making libraries for c++ often involves creating .a, .so, .dll etc. files of compiled code that new programs can link against, but arduino compiles everything from source for every sketch so you don't need to worry about that here.

To address your query about libraries making sketch code too big...
I have recently completed (or rather, am in the process of completing) my first library, SevenSegmentSL1255. I too was concerned about the growing size of the library, as I incorporated more and more ideas. So I decided to plan for a "Lite" version, SevenSegSL1255Lite, so that the casual user would not feel to overwhelmed and also to reduce the memory footprint, for simple sketches.
However, after reading the Arduino page on the build process, I discovered that the whole library is not necessarily included in all sketches:

The .c and .cpp files of the target are compiled and output with .o
  extensions to this directory, as is the main sketch file and any other
  .c or .cpp files in the sketch and any .c or .cpp files in any
  libraries which are #included in the sketch.
These .o files are then linked together into a static library and the
  main sketch file is linked against this library. Only the parts of
  the library needed for your sketch are included in the final .hex
  file, reducing the size of most sketches.

So you see, from a memory footprint point of view, no matter how big the library may be, the resultant compiled sketch can still be quite small, depending on the amount of the library that is called for the sketch. From my point of view, this makes the "Lite" version of my library now somewhat redundant. Although, the argument for a simpler, more user friendly library may still exist.
As an aside, the resources that I used in creating the library are listed below:

Writing a Library for Arduino
Arduino Style Guide for Writing Libraries
error in using overloaded constructor
Memory
Style Guide

True, as long as it's clear that the smallest unit that may be included or excluded is an entire library module, such as an EEPROM module. In the context, 'library' means 'collection of .o files, and 'parts of the library' means individual .o files. ...

... If your code doesn't call any functions contained in the EEPROM library module, and none of the library modules that you DO call makes any calls to the EEPROM module, then that module will not get linked into your code. If, however, there is one call to one tiny function in that module, the whole module will be linked (generally speaking; there is currently work being done delay all or most code optimization until link-time, which may possibly yield finer-grained inclusion/exclusion). Thus writing a Lite version or writing sub-modules may well be useful to keep the linked code image small.

@JRobert - Thanks, I may need to look into this further, as I appear to have mis-interpreted the quote in my answer.


text:
Arduino 16x2 LCD Black Boxes
I hooked up a 16x2 Arduino compatible LCD yesterday and made sure all the connections were according to the program and the schematics provided all over the web. My contrast is adjusted perfectly but the problem is that there are black boxes on the top line while the lower one is empty.

I know this question has been asked many times but no one has answered the question other than saying, "Check your contrast pin". I'm using the default sample code provided in the Arduino IDE.
HELP!
Regards.

Do you use a I2C interface on the LCD?

@RienBrand Nope. Just the standard interface(i dont know what its called).
Here's a link to its data sheet by the way:
http://www.evselectro.com/image/data/datasheet/LMB162ABC.pdf

Can you post a picture of how you connected it? Contrast, indeed, isn't the issue here.

Most commonly this kind of problem is because the display has been connected backwards.  Double check which pin of the header on your display is pin 1.

@Majenko The display can't possibly be connected backwards because the pins are labelled on the display itself. I didn't even have to look for the datasheet. Pin 1 and 2 are the power pins then we have contrast,RS,R/W,E and so on. And oh yeah R/W is connected to ground.

@Gerneb How? There's no option :/

Look at this answer here: http://arduino.stackexchange.com/a/17472/11174

Try in your code lcd(0x27,16,2); insted of lcd(0x3f,16,2);

I have done some Googling across the web and it turns out that this can be caused by a couple of things:

Incorrect wiring.
Wiring of LCD backwards (ie 1 to 16 and 16 to 1).
Faulty wiring (ie broken cables & dry joints).
Incorrect initialization of the LCD.
Buggy software.
Damaged screen.

The LCD screen that you have is a based on the Hitachi HD44780 chipset. It is the most common interface for text-based LCDs. It can be identified by the 16-pin interface. I2C is the next most common interface and is distinguishable as it has a 4-pin (sometimes 5-pin) interface.
Lets assume that your screen isn't damaged. From the details in your question, it sounds like your contrast is working just fine. The list above can be shrunk to just 2 things: bad wiring and/or bad code. Lets eliminate both of those by using known working software and known working circuit.
Arduino has an LCD library with example programs. Details for this library, including a wiring diagram, can be found over at the Arduino site in the Reference section. I use these example sketches to test my wiring connections before I write my own program. I recommend using the Autoscroll example.

Schematic:

These diagrams are from the Arduino Autoscroll page. I highly suggest that you read this page thoroughly.
The code can be easily uploaded into your Arduino, through the IDE, by going into File > Examples > LiquidCrystal > AutoScroll, then Sketch > Upload.
You should see the sketch print the characters 0 to 9 on the top line (with autoscroll off), then moves the cursor to the bottom right (turns autoscroll on,) and prints the characters 0 to 9 on the bottom line, but as it prints each character the display should move one to the left.
If you get this example program to work then you know that you have a working LCD and also that your wiring is OK as well.

Are you using an LCD driver board that has 4 connections between it and the arruino, or do you have the LCD directly connected?
If using a driver board, download Liquid Crupystal Library here
Ten make sure to have the library running in that startup code.

Connect your RW pin to Ground.

Your answer is rather terse and could do with some expansion. For example, why will connecting RW to ground help? As it stands your answer would have been better as a comment

Alright guys thanks for everything! I've found the solution. It was a bad solder.

Your contrast is just fine. The black boxes indicate that your LCD isn't correctly initialized. Poor connections and / or bad code is to blame. So focus your debugging there.


text:
Getting inverse values of acceleration and tilt for the MPU 6050
I'm using the I2C library to connect to a GY-521 board and, when executing the getAcceleration() methods I get gyro values and viceversa..
This is my setup (I'm using a proto shield but that shouldn't change anything as far as I understand):

It follows this schematic:

And this is the code I'm testing:
#include "Wire.h"

#include "MPU6050.h"

MPU6050 accel;

int16_t ax, ay, az;

void setup() {
    Wire.begin();
    Serial.begin(9600);
    Serial.println("Initializing I2C devices...");
    accel.initialize();
    Serial.println("Testing device connections...");
    Serial.println(accel.testConnection() ? "Connected" : "Connection failed");
}

void loop() {
    accel.getAcceleration(&ax, &ay, &az);
    Serial.print("acc x:    ");
    Serial.println(ax);  // This prints the gyro value of the Y axis!
    delay(1000);
}

I don't think it has to do with the wiring since inverting the 4 and 5 analog pins yields zero values.
Is this a problem with the library? Or with my chip?

I think this has to be a problem with the library, or with your method of discerning which set of values is the accel and the gyro I guess. Gyro should be the one totally zerod out when the sensor is sitting still. Where did you download the library from?

Yup I'm sure that's the gyro value (I even have a video if you need it). So I'm guessing it's the library... I may just wrap it up with the correct names

Personally I use accel.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); which yields all values generated by the sensor.
Just to be certain, if you use accelgyro.getAcceleration(&ax, &ay, &az); you get Gyro data and if you use accelgyro.getRotation(&gx, &gy, &gz); you get Accelerometer data?
If you actually get the values the wrong way around, you could just use the variables in the 'wrong' way, I know this is not how it should work.

There are a lot of libraries, I wouldn't use the accelerometer library in wire, download and add the I2Cdev library, you can get it on a variety of different sites like github.com

Would you please develop your answer further? Currently this is not the typical kind of useful answer: no real value, no detail, no reason why "you wouldn't use the accelerometer library..." For me, you could have posted this as a comment to the question.


text:
Do I have to use an external power supply when connecting an ultrasonic sensor to Arduino?
This might be a very stupid question but please bear with me. So I am using an HC-SR04 Ultrasonic sensor model (5 V) and I want to connect it to Arduino Uno. Do I have to use an external power supply for the ultrasonic sensor (just like with the motors) in order to connect it to the Arduino? Or can I just use the 5 V pin?

It is a low current device so yes you can connect it to the 5V pin, also consult the datasheet for setup stuff and current draw.

http://www.spiked3.com/?p=6021 - includes code without using libraries for arrays of SR04s

From the question I assume you power your Arduino via USB in which case you don't need an external supply. The HC-SR04 draws 15 mA with is far below the specifications for USB. I did this myself some time ago: