text:
How to implement server.on() without any libraries?
I was trying to setup a web server with Arduino and ESP32, without using the ESP32 libraries.
Currently I'm able to display a webpage(a form with single submit button) from the server, with only using AT commands.
But how can I receive GET/POST requests send buy the form fields?
In the WebServer.h library this is done by the method
    server.on("/actionPage", HTTP_GET, []() {
        server.sendHeader("Connection", "close");
        server.send(200, "text/html", "This is actionPage");
    })

I was wondering if there is a way to do this without libraries, I searched a lot, but didn't found a solution for this..
Thanks in advance!

Why, in gods name, would you choose to cripple an ESP32 with AT commands? You are currently using a Fiat Panda to tow a Lamborghini, in which you have placed a toddler to control it. Crazy, man...

@Majenko, it may be crazy, but is it doable?

Sure, it's doable. You just need to send the right AT commands to perform the task you need to do. Personally I wouldn't, but you do you m8.

@Majenko, I was just studying how the AT commands are used to configure a web server, and there are a lot of examples are available showing how to send GET/POST request from a local server to the ESP, But didn't found one regarding  how to receive GET/POST request from a client!!

just curious about how these things are done with AT commands..Even didn't know where these AT commands are stored in arduino libraries. It would be extremely helpful if you guys could give me any information regarding this, Thanks!

Until you raised the question, I didn't even know there was AT firmware for the ESP32. I have no idea how they chose to implement it. What does the manual for the AT firmware say?


text:
I2C Hangs (sometimes) when Wire->endTransmission() is called
Architecture

MKRZero
BME280 Atmospheric Sensor
SSD1306 128x64 OLED Screen
SparkFun GPS:

device: https://www.sparkfun.com/products/14414
arduino library: https://github.com/sparkfun/SparkFun_I2C_GPS_Arduino_Library

K30 CO2 Sensor:

device: https://www.co2meter.com/products/k-30-co2-sensor-module
arduino library: https://github.com/FirstCypress/K30_CO2_I2C_Arduino

System Setup

The system essentially just pulls measurements from these sensors every few seconds (adjustable), and writes them to Serial, to the OLED, and to an SD Card. Everything works fine and essentially forever when the K30 is not attached.
"Random" system freezes happen only once I attach the K30...
Once the K30 is attached to I2C, the system will run fine, recording and displaying data from all sensors (including the K30) for an indeterminate amount of time before "freezing." The every-so-often freeze happens during a call to my write_to_screen() function. The system will freeze during the first wire->endTransmission() that is called in the screen library (see library here). Usually that while loop executes a few times, the screen updates, and the program continues, but not when it freezes.
write_to_screen() Function

Screens are cycled using the blue button that increments the
  screen_page var.

// display info on oled screen
//
// - many different displays available, cycled using button one
//
void write_to_screen() {
  Serial.println(F("  - writing to screen"));
  display.clearDisplay();
  display.setCursor(0,0);

  // default data display
  if(screen_page == 0) {
    display.setTextSize(2);
    // print co2
    display.print(F("CO2:"));
    display.println(co2);
    // resize text
    display.setTextSize(1);
    // print temp
    display.print(F("Temp: "));
    display.print(temperature_c);
    display.print(F("C "));
    display.print(temperature_f);
    display.println("F");
    // print humidity
    display.print(F("Humi: "));
    display.print(humidity);
    display.println(F("%"));
    // print pressure
    display.print(F("Pres: "));
    display.print(pressure);
    display.println(F(" hPa"));
    // print altitude
    display.print(F("Alti: "));
    display.print(gps.altitude.meters());
    display.println("m (GPS)"); // gps altitude is presumably more accurate/precise
    // print lat/lon
    display.print(F("LtLn: "));
    display.print(gps.location.lat());
    display.print(F(", "));
    display.println(gps.location.lng());
    // print time
    display.print("Time: ");
    display.print(gps_to_time());

  // k30
  } else if(screen_page == 1) {
    display.setTextSize(2);
    display.println(F("K30"));
    display.print(F("CO2:"));
    display.println(co2);
    display.setTextSize(1);
    display.println(F("\n\nAdd a time graph?"));

  // bme280
  } else if(screen_page == 2) {
    display.setTextSize(2);
    display.println(F("BME280"));
    display.setTextSize(1);
    // print temp
    display.print(F("Temp: "));
    display.print(temperature_c);
    display.print(F("C "));
    display.print(temperature_f);
    display.println(F("F" ));
    // print humidity
    display.print(F("Humi: "));
    display.print(humidity);
    display.println(F("%"));
    // print pressure
    display.print(F("Pres: "));
    display.print(pressure);
    display.println(F(" hPa"));
    // print pressure based Altitude
    display.print(F("Alti: "));
    display.print(altitude);
    display.println(F("m"));
    // print gps based altitude
    display.print(F("Alti: "));
    display.print(gps.altitude.meters());
    display.println(F("m (GPS)"));

  // gps
  } else if(screen_page == 3) {
    display.setTextSize(2);
    display.println(F("GPS"));
    display.setTextSize(1);
    if( is_gps_valid() ) {
      display.println(gps_to_datetime());
      // print sats
      display.print(F("Sats: "));
      display.print(gps.satellites.value());
      display.println(F(" (# of)"));
      // print lat/lon
      display.print(F("LtLn: "));
      display.print(gps.location.lat());
      display.print(F(", "));
      display.println(gps.location.lng());
      // print gps based altitude
      display.print(F("Alti: "));
      display.print(gps.altitude.meters());
      display.println(F("m"));
      // print pressure based altitude
      display.print(F("Alti: "));
      display.println(altitude);
      // print hdop
      display.print(F("HDOP: "));
      display.println(gps.hdop.value()/100.0);
    } else {
      display.println();
      display.println(F("Sats: 0 (NO SAT LOCK)"));
      display.println(F("LtLn:"));
      display.println(F("Alti:"));
      display.print(F("Alti: "));
      display.print(altitude);
      display.println(F("m (BME)"));
      display.println(F("HDOP:"));
    }

  // init statuses
  } else if(screen_page == 4) {
    display.setTextSize(1);
    display.print(F("Carbon Cutter "));
    display.print(ccversion);
    display.print(F("\nby Dan & Brian"));
    display.println(gps_to_datetime());

    // display init statuses
    // I2C and screen -- if we're reading data here, they are working
    //display.println("I2C Init:" + get_init_status(i2c_init) );
    //display.println("Screen Init:" + get_init_status(screen_init) );
    display.println(F("K30:    DEV"));
    display.print(F("BME280: "));
    display.println(get_init_status(bme280_init));
    display.print(F("GPS:    "));
    display.println(get_init_status(gps_init));
    display.print(F("SD:     "));
    display.println(get_init_status(sd_init));
    display.print(F("File:   "));
    display.println(get_init_status(file_init));
  }

  display.display();
  Serial.println(F("  - done writing to screen"));
}

Unplugging SDA Wire Unfreezes I2C
I can unplug the K30's SDA wire and the system will resume, again, for some amount of time before it freezes again, when I can once again, unplug the K30 SDA wire and things will resume. Sometimes it will run for ten minutes. Other times for a few seconds/cycles. When it's running, data is pulling fine, and I2C seems to be working fine (I'm testing with a PicoScope). When I unplug the K30 SDA wire, the text on the screen updates and is garbled (sometimes wrong text in the wrong spot, and sometimes just messed up pixels) until I2C resumes working.
System / I2C Working Fine

System / I2C Frozen

I've fixed 50 things in my code that I thought were the root cause here, but none of them have stopped this very specific freeze event. I thought it was a memory issue for a while. I chased that, and don't think that's the problem, but I'm not truthfully sure.

That sounds as if the K30 is blocking the SDA line from getting high again. How does it work, if you only check the K30?

The system runs fine if I never call write_to_screen() ... I2C never hangs and I can retrieve data from the K30 with no problem via I2C, seemingly indefinitely. My "freezing" problem is especially confusing because writing to the Screen via I2C causes an I2C problem that is resolved by disconnecting the K30 from I2C.

As you have a scope: Can you try to catch the problematic transmission on the scope (you could change the display library to set a pin as trigger signal). That way we could see, in what communication step the problem happens. Also you can try to find out, if the K30 really is holding SDA low, by disconnecting the K30's SDA pin from the bus (but still with a pullup resistor on it) and check, if it is still low. If yes, the K30 is really the culprit.

Did you happen to solve the problem ? I'm in the same situation,just a bit different, my setup is just having a GNSS F9P and an SSDSSD1306. Eventually when trying to write to the display the SDA and SCL lines stay low, if I disconnect the display then all the data begin to flow again ...

source: Stack Exchange

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

sort: votes


text:
I need help with U8GLIB library
I have a project which uses a 128x64 oled display. I have to use the U8GLIB as the available displays change from SSD1306 to SSH1106 depending on when you buy it which that library covers both displays.
I don't want the program for the display to eat up the memory of the arduino so I use u8glib instead of u8g2! for this project I need to display numbers 0 to 9, decimal point, omega (ohm symbol) and metric prefixes such as μ,m,k,M, etc...
I first tried to create a bitmap font (.bdf) and convert it to a C file because that was what was hinted at on a few posts. There were no tutorials and after messing about with the different formats and trying to add the font to the library I just gave up because I couldn't figure it out. Instead I decided to use this website which generates bitmaps from TTF files:
https://littlevgl.com/ttf-font-to-c-array
Now I can use those bitmaps and have my few characters which use very little memory (about 20% as opposed to more than 70% using a complete symbols font in u8g2!) but this makes things really awkward as I have to translate every number I get into separate digits and then into a bitmap! also I can only use font sizes which have a height in multiples of 8 because for some weird reason this library expects width in number of bytes and height in number of pixels!

cnt: Number of bytes of the bitmap in horizontal direction. The width
of the bitmap is cnt*8.

so I can do fonts of size 48 for example, but not 50 or 52 which would be more suitable for my application!
I'm not sure if anyone else has had this issue but there must be a way to display the characters you want without destroying your entire memory space like u8g2 does! Just getting to this point took me 2 days (on the left there is a 0.96" SSD1306 and on the right there is a 1.3" SSH1106):

Please help if you have any idea on how to deal with this library as it's driving me insane at the moment!

While this may not exactly answer your question, there may be some information about u8g2lib that you have not seen. The library source code is linked here: u8g2lib
Within that repository is the FAQ documentation which includes such gems as:

Q: U8g2 requires a lot of memory. How to reduce this?
  - Visit https://github.com/olikraus/u8g2/wiki/u8g2optimization
  - Disable U8g2 features if possible (see u8g2.h)
  - Limit the font size. If possible avoid "f" fonts, instead use "r" or "n" fonts
  - If the I2C interface is not required, then uncomment #define U8X8_HAVE_HW_I2C in U8x8lib.h   (Background: Due to a problem in
  Wire.h, the I2C Arduino lib is always included)

and

Q: How can I generate my own font. A: The font must be available in
  bdf file format. Then use bdfconv to generate the font data. The font
  data can be pasted into an existing file of your project. There is
  also a nice Windows Bitmap Font Editor "Fony"
  (http://hukka.ncn.fi/?fony)  which can export .bdf files. A copy of
  Fony 1.4.7 is available here:
  https://github.com/olikraus/u8g2/tree/master/tools/font/fony

The tools/font directory includes several utilities, including what looks like one that converts OTF fonts to BDF format
Once you get a BDF format font, you use bdfconv to create the C file that holds the font array. One of the arguments for bdfconf is the -m 'map' option. You can place in there a list of Unicode ranges that limit which characters get included. So, you can create a font that has ONLY the characters you need.
For example -m '45-46,48-57,77,107,109,181,937' gets you minus, decimal, 0-9, 'M', 'k', 'm', mu, omega. Unicode character map at https://unicode-table.com/en/
The benefit to creating a font is that the u8g2lib library itself does all the mapping to bitmaps and calculating the character widths, etc. so you don't have to.

this is really helpful,specially with memory reduction part, but I'm still not sure how to use the bdfconv tool, it seems to be used with linux command line, not windows. Also even when I get the C file, I'm not sure how to use it. should I add something to the u8g2_fonts.c? should I just copy and paste the generated file into my .ino sketch? please link to a full tutorial if you can, or at least create a basic walk through, thanks!

I'm not sure there is a full tutorial. Look in https://github.com/olikraus/u8g2/tree/master/tools/font/bdfconv for a .exe windows version of bdfconv!. The resulting .c font file: Just #include "fontfile.c" in your program, and put the file in the same folder as your sketch. That will bring in the font without having to edit the existing fonts file.

when I run the .exe file nothing happens. Should I download and modify the "  Makefile" as well? The instructions are really vague and lacking tbh.

I downloaded https://github.com/olikraus/u8g2/blob/master/tools/font/bdfconv/bdfconv_2_22.exe and it runs fine.

does it not require any other files and runs on it's own? for me it opens and closes immediately afterwards! I think I have to stick with creating manual bitmaps :(

You have to run it from a command prompt. It's not a graphical program.

Another note -- if the fonts you want to use are taking up 70% of flash space, but you aren't hitting 100%, then what's the problem?

because it's the display aspect of the program only! if I add the rest of the project, it won't fit!

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


text:
Weird problem with arduino
I wrote the code below and the result is not what I expected at all! I'm not sure why it's happening!
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

const uint8_t pat[] PROGMEM = {
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x66
};

void loop() {
  delay(100);
  Serial.println(sizeof(pat));
  for (int i=0; i<8; i++){
    Serial.print(pat[int(i)],HEX);
  }
  Serial.println("");
  Serial.print(pat[0],HEX);
  Serial.print(pat[1],HEX);
  Serial.print(pat[2],HEX);
  Serial.print(pat[3],HEX);
  Serial.print(pat[4],HEX);
  Serial.print(pat[5],HEX);
  Serial.print(pat[6],HEX);
  Serial.print(pat[7],HEX);
  Serial.println("");
  while(true);
}

the output is surprisingly this:

8
008000010
FF0FF0FF0FF66

What is compiler doing in the background but it seems to be messing things up really bad! The loop should be doing the exact same thing as manually writing that code over and over but it's not! How can I fix the loop?

does the output represent one iteration of loop()?  .....  you really need to print a delimiter by using something like Serial.println("--------------");

If you want to get a value from PROGMEM you must read it with pgm_read functions. Read the PROGMEM reference.
for (int i = 0; i < 8; i++) {
  Serial.print(pgm_read_byte_near(pat + i),HEX);
}

pat[0] in Serial.print(pat[0],HEX); is an item in a constant array const uint8_t pat[]. it can't change at runtime so the compiler uses the value 0xFF. that is why it is printed ok without pgm_read_byte_near

that would explain it, but why when I write pat[6] manually in print statement, it doesn't return the same value? somehow only the loop values are replaced at compile time?

@OM222O, as I write in the answer, the constant uses are replaced at compilation

My question still remains: Why is the code in the loop SPECIFICALLY replaced during compilation? if I do something i=0; print(pat[i]); it should not be different to print(pat[0]); ! it's almost as if the compiler is treating integers differently!

because using the value from the array position requires less instructions then getting the value from the array every time. the compiler optimizes for small size of the binary

that wouldn't make a ton of sense! they're both ints! I even made sure to use int(i)! The int is created and the increased ever cycle the program runs!

@OM222O, pat[0] in Serial.print(pat[0],HEX); is an item in a constant array const uint8_t pat[]. it can't change at runtime so the compiler uses the value 0xFF. that is why it is printed ok without pgm_read_byte_near


text:
How to save a state - make an arduino run a code only once/make aruduino bahave differently the next time he is on
Im building a arduino based bicycle speedometer. When the code starts the user picks his bike size (which I need to calculate the radius). Then I have a state finite machine where the user taps the button between speed, time and temperature. I need to put this circuit on a battery and it needs to be mounted on a bike. But every time you plug and unplug the battery, the code runs from the beginning again, which I don't want. So every time the user turns the speedometer off then on, he needs to pick his bike size again. Is it possible to save the size he has picked so that the next time he turns it on, it doesn't come across.
So - user has his speedometer, turns it on, picks the bike size, turns it off, then sometime later turns it back on and the part for picking the bike size doesn't show up, it simply "knows" remembers what the user picked last time.
I don't know how could that work, would the Arduino run the certain code only once or is there a function for "the next time Arduino has electricity behave like this".

use the EEPROM library

As one of the comments said, you will need to use the EEPROM library. When you save a variable in your code (e.g. int test = 10;) the variable along with its value gets stored in the RAM. The EEPROM is a piece of harddisk on your arduino that will remember its value when you power off your arduino.
If you implement a power-off button, simply save the state (or in your case, the wheel size) in EEPROM whenever the user inputs it. The next time you power up, you can check if there is a previous value in EEPROM and continue with that value if it exists. Otherwise ask the user for their wheel size.
You might want to implement a reset-button as well, to reset whenever you change bike or wheels. Look up a code example of EEPROM, as there are a lot online.

Alright, thanks. I will look it up, this part "the next time you power up, you can check if there is a previsus value" - that is what I need. And yeah I will implement a reset button, good idea.
Cheers man :)

@MarinFilipovic don’t forget to read eeprom, it will not be in the variable you stored previously

ahaa okay, I get it, thanks


text:
How to connect HC-06 BT module without pins?
So, from one popular Chinese  store I ordered a HC-06 module that I received... and due to some mistake from a store, I received a HC-06 without connecting pins. So usually HC-06 looks like this (with blue plate underneath where 4 pins are available to solder or connect):

I just received the one without this blue plate and pins:

How do I connect it to Arduino if there are no pins? Where are usual GND, TX, RX pins (is this schematics correct?)? Is it okay if I just solder a wire to some of them without this blue under-plate?
Also do I need to add some resistors or other components if I connect wires directly to these half-circle pins?
Thank you!

The small green PCB is the real HC-06 board. The blue board has 2 functions:

It breaks out the contact pads of the HC-06 to the bigger pins.
It has a voltage regulator on it so that you can provide it with 5V power, which then get's converted to 3.3V for the HC-06 (which is a 3.3V device).

The next steps depend on what Arduino board you have:

If you have a 3.3V Arduino Board, you can directly connect the pads on the HC-06 (by soldering pins or wires to them) to the corresponding Arduino pins:
Arduino <--> HC-06
  3.3V  <--> 3.3V
  GND   <--> GND
  TX    <--> RX
  RX    <--> TX

Also you can connect a fitting LED to the LED pin. I spontaneously cannot find data about the max current of this pin. But I guess it is in the range of 10 to 20 mA. Use a corresponding combination of an LED and a resistor.
If you have a 5V Arduino, you need to consider the voltage difference. On the Uno and Nano you have a 3.3V regulator on board. The regulator itself is rated for 150mA, but since it is not cooled, the limit is more like 50mA (see this forum thread). This datasheet of the HC-06 states, that it draws at max 30-40mA, so you can get away without an extra 3.3V regulator, just by connecting the both 3.3V pins on Arduino and HC-06. If the voltage regulator overheats despite being under 50mA, you need to buy an extra 3.3V voltage regulator, that can handle the current.
Don't forget to use a voltage divider on the Arduino-TX --> HC-06 RX line to divide the Arduinos 5V down to 3.3V. This line isn't even regulated by the blue breakout board, so you would need this voltage divider either way.
Ground connection and the LED are the same as in the first case.

So all in all you can still use the HC-06, just with a little bit less ease than with the blue breakout board.

So in order to use my voltage divider I have to connect 3.3V of HC-06 to the same 3.3V on my Arduino Nano board? Will it overheat then?

Connecting both 3.3V pins between Arduino and HC-06 is for the power supply. My guess is, that it won't overheat. But I have to state, that it goes rather near the limit of 50mA. I wrote it the way above, to state, that I cannot be sure about it. With an extra voltage regulator, that can provide more current, you will definitely be safe. It is your decision, if you want to try it without.


text:
What are these stray resistors on the Arduino Mega schematic?
I am using the Arduino Mega schematic found here and it's mostly clear, but there are a few resistors floating in the middle and I'm not quite sure what they're for or where they go:

Does anyone know what these are and where they go?

Those are unused resistors in resistor arrays.  The arrays have 4 resistors side by side in a single package. Not all of the elements are always needed, but they have to be in the schematic anyway since they exist in real life.

Elements A and D of Resistor Network 1 (RN1)
Elements B and C of Resistor Network 2 (RN2)
Element C of Resistor Network 3 (RN3)

That's why many EDAs/ECADs have a "not connected" symbol (usually a "x" of some kind) to make clear that something is left unconnected on purpose (and not because the designer forgot to connect it). Also, when checking the nets, they'll raise an error for those "forgotten" pins.

@Flyingfenix Indeed. But eagle is either useless, or frequently abused by people without a clue.  Personally I never use it...

Isn't this a packaging detail? Not every resistor has to come in arrays of 4. Seems like a horrible decision to include it on the schematic.

@Tvde1 No, not every resistor has to come in arrays of 4. But it can be cheaper to use an array of 4 instead of 2 individual resistors. And since an array has 4 resistors you end up with 4 resistors in your schematic. I don't personally like the way it's done there either - I prefer to have a single component that has 4 resistors and 8 pins - that way you can more easily visualise which pins are going where to make routing of traces on the PCB simpler.

@Tvde1, it can also be less expansive and easier to manufacture to have fewer different components. A pick and place machine only has so many part cartridges, so to avoid having to run the boards through again, or having to place them manually, they reduce the types of parts. Also, this goes into the idea of cost scalability for parts. If you can get 10% off for using a part 10% more, then you've saved some money in manufacturing your board.


text:
Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee
I want to create a growhouse sensor system. I have an Arduino UNO, wireless SD shield and I have just ordered a series 2 XBee XB24.
Any info I find seems to revolve around having 2 Arduinos and 2 XBee modules, why is that?
I am presuming that once I connect the XBee to the shield that I can then connect to my Arduino on the network and send and receive data, am I wrong?
I'm a developer and sysadmin but a noob to Arduino so any help is much appreciated.

Do you remember the term mesh network? Xbee's create a mesh network or multipoint network using 802.15.4 (hurray for google) protocol. This is not compatible with 802.11, the wifi protocol.
If you want everything to talk, you are either going to need to get an Xbee for everything, or wi-fi for everything (or wi-fi + ethernet for that matter).

The xbee network and the wifi network are both wireless networks, but, they do not communicate with each other.
You have two options.

Attach a second XBEE to your computer using one of these
https://www.sparkfun.com/products/11812
Get a WIFI shield http://arduino.cc/en/Main/ArduinoWiFiShield

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


text:
Arduino Uno wiring and code with Parallax PMB-688
I'm new to Arduino GPS and am wondering if I could be pointed in the right direction regarding code and wiring when hooking up my Parallax PMB-688 to an Arduino Uno

Try this: http://playground.arduino.cc/Tutorials/GPS -

The following link was suggested in the comments by user PhillyNJ. Adding it here as a community wiki answer:

http://playground.arduino.cc/Tutorials/GPS

authors: Антон Лабозин

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


text:
Is it possible to program a few Arduinos at the same time?
I have 10 Arduino Pro Minis and one Arduino Uno. Via breadboard, if I connect Pro Minis in parallel, can I program all of them at same time?
Is it possible?

What problem are you trying to solve?

@IgnacioVazquez-Abrams I've 60 Arduino Pro Minis and all of them need to be programmed same. I just wanted to do this 10 by 10.

https://www.sparkfun.com/products/11591

Arduino Pro Mini is programmed through serial, using a bootloader. It uses STK500 protocol, which is described by Atmel.
In theory, it can be possible to program multiple boards if only one TX Arduino pin is connected to USB-Serial converter, and all RX are in parralel, but this is an unreliable method. Only the board with TX pin connected can send its status back to programmer.
Arduino Mini also requires a physical reset before uploading. Make sure that all Reset pins are connected together when reset button is pressed.

Thank you, may ask, is it worth to risk? What can be go wrong?

Noting that the avrdude using STK500 protocol expects responses, which is initially accommodated above by "only one TX pin connected" However, this will be very very problematic, as the "only TX" will likely respond (even occasionally or just once) before the other slaves are not ready and such slaves will fall out of sync. I have done just this on a different product(not AVR) and we had to add long delays on the Master (avrdude in this case) to after it got the response to ensure all the slaves had a chance to catch-up. Likely will not be able to do the same here.

In this case I would recommend considering using multiple USB-to-Serial Ports and simply replacing the ".\arduino-1.5.6-r2\hardware\tools\avr\bin\avrdude.exe" with a batch file that then called 10 (or any number of Serial Ports) of your choice.

I would recommend reading my answer from Programming Arduino's from a centralized location.
Where that solution may be a bit more complicated, then needed. But the same pieces would allow you to create a custom programmer that can specifically call the custom avrdude. Allowing the original methods to still exist.

Additionally worth noting. Is that you can turn on verbose for the compiling and uploading from the IDE's preferences. This will display the temporary directory that contains the exact location of the bin file and command executed to upload. Which can then be easily re-executed your convenience. Noting the temporary directory is not immediately destroyed. Where you can also change the arguments to execute different ports and sending it to the background. To call others. So that you can simultaneously upload many devices.


text:
Enabling quicker and more accurate MindWave Mobile detection?
Currently I am trying to get a Mindwave Mobile device to operate with an Arduino Uno. I'm following the guide here.
However the sample code given doesn't work very well. I have been trying to get a more consistent output but to no avail.
MindWave Code :
#include <SoftwareSerial.h>     // library for software serial
SoftwareSerial mySerial(5, 6);  // RX, TX
int BAUDRATE = 57600;

// checksum variables
byte payloadChecksum = 0;
byte CalculatedChecksum;
byte checksum = 0;              //data type byte stores an 8-bit unsigned number, from 0 to 255
int payloadLength = 0;
byte payloadData[64] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;
boolean brainwave = false;

void setup() {
  Serial.begin(57600);       // Bluetooth
  delay(500);
  mySerial.begin(4800);      // software serialz
  delay(500);
  Serial.print("Communicating... ");
  mySerial.print("Communicating... ");
  mySerial.println();
}

byte ReadOneByte() {
  int ByteRead;
  // Wait until there is data
  while (!Serial.available());
  //Get the number of bytes (characters) available for reading from the serial port.
  //This is data that's already arrived and stored in the serial receive buffer (which holds 64 bytes)
  ByteRead = Serial.read();
  return ByteRead; // read incoming serial data
}

unsigned int delta_wave = 0;
unsigned int theta_wave = 0;
unsigned int low_alpha_wave = 0;
unsigned int high_alpha_wave = 0;
unsigned int low_beta_wave = 0;
unsigned int high_beta_wave = 0;
unsigned int low_gamma_wave = 0;
unsigned int mid_gamma_wave = 0;

void read_waves(int i) {
  delta_wave = read_3byte_int(i);
  i += 3;
  theta_wave = read_3byte_int(i);
  i += 3;
  low_alpha_wave = read_3byte_int(i);
  i += 3;
  high_alpha_wave = read_3byte_int(i);
  i += 3;
  low_beta_wave = read_3byte_int(i);
  i += 3;
  high_beta_wave = read_3byte_int(i);
  i += 3;
  low_gamma_wave = read_3byte_int(i);
  i += 3;
  mid_gamma_wave = read_3byte_int(i);
}

int read_3byte_int(int i) {
  return ((payloadData[i] << 16) + (payloadData[i + 1] << 8) + payloadData[i + 2]);
}

void loop() {
  // Look for sync bytes
  // Byte order: 0xAA, 0xAA, payloadLength, payloadData,
  // Checksum (sum all the bytes of payload, take lowest 8 bits, then bit inverse on lowest
  if (ReadOneByte() == 0xAA) {
    if (ReadOneByte() == 0xAA) {
      payloadLength = ReadOneByte();
      if (payloadLength > 169) //Payload length can not be greater than 169
        return;
      payloadChecksum = 0;
      for (int i = 0; i < payloadLength; i++) {     //loop until payload length is complete
        payloadData[i] = ReadOneByte();             //Read payload
        payloadChecksum += payloadData[i];
      }
      checksum = ReadOneByte();                     //Read checksum byte from stream
      payloadChecksum = 255 - payloadChecksum;      //Take one’s compliment of generated checksum
      if (checksum == payloadChecksum) {
        poorQuality = 200;
        attention = 0;
        meditation = 0;
      }
      brainwave = false;
      for (int i = 0; i < payloadLength; i++) { // Parse the payload
        switch (payloadData[i]) {
          case 02:
            i++;
            poorQuality = payloadData[i];
            bigPacket = true;
            break;
          case 04:
            i++;
            attention = payloadData[i];
            break;
          case 05:
            i++;
            meditation = payloadData[i];
            break;
          case 0x80:
            i = i + 3;
            break;
          case 0x83:                         // ASIC EEG POWER INT
            i++;
            brainwave = true;
            byte vlen = payloadData[i];
            //mySerial.print(vlen, DEC);
            //mySerial.println();
            read_waves(i + 1);
            i += vlen; // i = i + vlen
            break;
        }                                 // switch
      }                                   // for loop

/*
      if (bigPacket) {
        if (poorQuality == 0) {
        }
        else {                            // do nothing
        }
      }
*/
      if (brainwave && attention > 0 && attention < 100) {
        mySerial.print(attention, DEC);
        mySerial.println();

        Serial.print(attention, DEC);
        Serial.println();
      }
    }
  }
}

Often, the serial monitor stops display new values that stems from the Mindwave. Any suggestions on how I could modify the code to get it to run more smoothly will be greatly appreciated.

No use in reinventing the wheel!

Brain is an Arduino Library for parsing data from Neurosky-based EEG
  headsets. Tested units include the Star Wars Force Trainer and Mattel
  MindFlex.
It's designed to make it simple to send out an ASCII string of
  comma-separated values over serial, or to access processed brain wave
  information directly in your Arduino sketch. See the examples for code
  demonstrating each use case.

https://github.com/kitschpatrol/Brain
Install the library, and set it up like this:
#include <Brain.h>

// Set up the brain parser, pass it the hardware serial object you want to listen on.
Brain brain(Serial);

void setup() {
// Start the hardware serial.
Serial.begin(9600);
}

void loop() {
// Expect packets about once per second.
// The .readCSV() function returns a string (well, char*) listing the most recent brain data, in the following format:
// "signal strength, attention, meditation, delta, theta, low alpha, high alpha, low beta, high beta, low gamma, high gamma"
    if (brain.update()) {
    Serial.println(brain.readErrors());
    Serial.println(brain.readCSV());
    }
}

Can't guarantee that it will work, but if you have the TX pin of the bluetooth hooked up to the RX pin of the Arduino I'm pretty sure it will work.

I have just spotted this question because I had a similar issue: the while condition reading Serial data is blocking.
I've rewritten the parsing part a little bit, which you can see here.
This makes it smoother to run things in parallel, but it takes about the same time to accumulate a big packet of brainwave data.


text:
MKS GEN board pinouts for Arduino MEGA
As per this SO:
Is the MKS GEN V1.2 compatible with Arduino IDE as Arduino MEGA Board?
the MKS GEN board is an Arduino MEGA board mixed with other circuits.
My questions is how does it correlate with the Arduino Mega Board pinouts, especially the ones encircled in red below:

E.g. for connector Jc_M2 where does the EN, STEP and DIR pins connect to the ATmega2560 controller? And also for the other servo controller pins.


text:
Arduino code not working
Basically its an arduino project in which i am using an analog temperature sensor ky 013. The sensor is reading the temperatures correctly but what i want is to print the temperatures showed on the serial monitor to a lcd screen. I did the wiring and everything correctly  but there is something wrong with the code which i couldnt figure out.
Here is the code.
#include <math.h>

#include <LiquidCrystal.h>
LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

const int sensorPin = A0;
int switchState=0;

double Thermistor(int RawADC)
{
    double Temp;
    Temp = log(((10240000/RawADC) - 10000));
    Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
    Temp = Temp - 273.15;
    return Temp;
}

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    pinMode(sensorPin,INPUT);
}

void loop()
{

 switchState=digitalRead(sensorPin);
 int readVal=analogRead(sensorPin);
 double temp =  Thermistor(readVal);
 Serial.print("Temp. : ");
 Serial.print(temp);
 Serial.println(" Celsius");
 lcd.clear();
 lcd.setCursor(0,0);
 lcd.print("Temp: ");
 lcd.print(temp);
 lcd.print(" C");
 delay(500);
}

Please edit your post and format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

You haven't actually said what's wrong. If we don't know what's happening, we can't tell you why happening.

Have you checked if the pin defining is right for the LCD?

Does the lcd show "Temp: " as expected?

Please format your code.  I know it takes longer, but the payoff is in readability and maintainability.  It's well worth the extra effort.
LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

const int sensorPin = A0;
int switchState = 0;

double Thermistor(int RawADC)
{
    double Temp;
    Temp = log(((10240000 / RawADC) - 10000));
    Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp)) * Temp);
    Temp = Temp - 273.15;
    return Temp;
}

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    pinMode(sensorPin, INPUT);
}

void loop()
{
    switchState = digitalRead(sensorPin);
    int readVal = analogRead(sensorPin);
    double temp = Thermistor(readVal);
    Serial.print("Temp. : ");
    Serial.print(temp);
    Serial.println(" Celsius");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp: ");
    lcd.print(temp);
    lcd.print(" C");
    delay(500);
}

I think the problem is the
lcd.print(temp);

Try casting it to a float from a double (and two decimal places).  Maybe you just need the decimal places.
lcd.print((float)temp, 2);


text:
ATMega328P-PU not working
I bought some material on the net to start working with Arduino. I didn't want to buy an Arduino, since it costs a bit too much IMHO, so I bought an ATMega328P-PU, and made an Arduino on a breadboard. However, when I use my USBasp to program it it says that he can't set sck period (settings are: Arduino Uno as Board, USBasp as Programmer). It says that it has loaded the bootloader/program anyway, so I tried to go on and ignore it. The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works). Here I describe the circuit:

First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);
1st pin, Arduino Reset -> also to USBasp RST;
7th pin, Arduino VCC -> directly to 5V (and USBasp VCC);
8th, GND -> directly to Ground (and USBasp GND);
9th, XTAL -> to one pin of the 16MHz Crystal Oscillator, and to 22 pF capacitor, which connects to ground (not the pin);
10th, XTAL -> exactly as above, but it's connected to the other pin of the same crystal;
17th, digital 11 -> USBasp MOSI;
18th, dig 12 -> USBasp MISO;
19th, dig 13 -> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);
20th, AVCC, and 21st, AREF -> directly to 5V;
22nd -> directly to ground (not pin).

The can't set sck period message has to do with the USBasp. I get the same message every time I upload. It will still upload just fine.

Pin 1 (reset) should have a pull-up to +5V, not to Gnd.

@NickGammon sorry, I misread the guide... Thanks!

With your help, now it works. it was probably the resistor. Now I'm waiting for Mikael Patel's answer, but probably that wasn't the problem. However, it may cause some in the future

First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);

So it's permanently in RESET mode then? How can it ever do anything if you're holding it in RESET all the time?
RESET should be pulled UP by the resistor, not DOWN.

That was a nice catch!

Yeah, I misread the guide... Thank you a lot!

The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works).
19th, dig 13 -> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);

The lamp needs to be low power (< 20 mA) to work this way. If it uses more power you will burn the MCU pin.
Use a LED and a resistor instead. Or at least use a voltmeter.

21st, AREF -> directly to 5V;

This is not a good idea. Should be capacitor to ground. See for instance Uno schematics.
Cheers!

How many Farads? In the schematics I can't find it... By the way, thanks! I'll use my voltmeter.

Follow the AREF from the upper right connector and there it is 100nF. For more details http://www.avrfreaks.net/forum/capacitor-aref-atmega328

Ok, i need to buy those... I've only got 22 pF ones. Thanks a lot!


text:
How to interface arduino nano with sim900A?
I have arduino nano and sim900a modem.

Rx(pin30) and Tx(pin31) pins of arduino shows 3.8VDC respectively and Rx and Tx of SIM900a shows 3.6VDC and 2.8VDC respectively. Could i connect the SIM900a modem directly to the arduino? Since Should i use level shifter between arduino TX(3.8v) and SIM900A modem(3.6v)? Any suggestions?
Thanks..

Given that it has a 9-pin D-sub and is not suspected of being differential, one would ordinarily expect RS232 voltage levels which would destroy your Arduino, and are also inverted in polarity.  However, it's not clear where the level shifting to that from the likely low-voltage signals of the SM900A itself is happening.  Can you show the back side of the board?   Do not rely on voltmeter measurements  for serial lines.

Thanks for the reply Chris. Are you asking SIM900A  back side?

No, the circuit board.  The Sim900 is only the little rectangular metal can.

@ChrisStratton i've posted the image.

The bottom of your board shows a chip that gives every hint of being a charge-pump logic-level to RS232 inverting level shifter, to translate from the SIM900A's levels to the RS232 D-Sub connector.
It would appear that the 3 pin header just inside the D-sub would allow you to communicate at these levels.
However, a quick look at the SIM900A docs I could find suggests that these logic levels may be 2.8v, NOT 3.3v, and 3.3v is actually outside absolute maximum rating!
Essentially, you have two problems:

You need to drive and read signals with 2.8v logic, either by modifying your arduino to run at that voltage, or by using a level shifter.  It's possible that a resistor would protect the SIM900A, but that is going to be the most expensive component and so short of finding solid evidence of input protection diodes I'd be more hesitant to do that here than I would in other cases.
You need to make the level shifter not drive a signal into the SIM900A, so you don't fight with it.  You could do this by looking in the documenation (if any) for your board and seeing what accommodations they made for this, looking up the level shifter's  data sheet and finding the enable pin, or merely desoldering it.

Another option would be to make your Arduino talk at RS232 levels using its own shifter board.
Finally, there's a sort of hackish option:  Connect the transmit data from the SIM900A to a 3.3v Arduino, but connect the transmit from the Arduino through a simple inverter (tinylogic, whatever) to the RS232 receive pin.

Hi Chris. I've designed a simple voltage divider circuit for arduino tx to modem rx. Now its working.


text:
Custom Arduino library problem
I have made my custom serial(UART) library.
So I made uart.h and uart.cpp files as following.

uart.h

#ifndef UART_H
#define UART_H

#include <avr/io.h>
#include <stdlib.h>

//creating class named uart
class uart{

  public:

    // creating constructor
    uart(void);

    //function to start uart at given baudrate
    void start(int baudrate);

    // function to read uart input
    unsigned char read();

    // function to print data on serial monitor
    void print(unsigned char data);

    // function to print string on serial monitor
    void print(char *string);

    // function to print data with given base
    void print(unsigned char data,unsigned int base);

    //function to print data like printf
    void print(char* str,unsigned char data);

    // function to read data by printing string
    unsigned char read(char* string);

};

#endif

uart.cpp

#include "uart.h"

uart::uart(void);

void uart::start(int baudrate){

    long BAUDRATE = ((F_CPU)/(baudrate*16UL)-1);

    UBRR0H = (BAUDRATE >> 8);

    UBRR0L = BAUDRATE;

    // enable recieve and transmit
    UCSR0B |= 1 << RXEN0 | 1 << TXEN0;

    // data size is equal to 8 bits
    UCSR0C |= 1 << UCSZ00 | 1 << UCSZ01;
}

unsigned char uart::read(){

    //wait until receive complete.
    while(!(UCSR0A & (1 << RXC0)));

    // return received byte
    return UDR0;
}

void uart::print(unsigned char data){

    // wait until UDR is empty
    while(!(UCSR0A & (1 << UDRE0)));

    //place data into UDR
    UDR0 = data;
}

void uart::print(unsigned char* string){

    int index = 0;

    // print string character by character
    while(string[index] != '\0'){

        print(string[index]);

        index++;
    }
}

void uart::print(unsigned char data,unsigned int base){

    //buffer to store converted data
    char buffer[10];

    //convert data to ascii
    itoa(data,buffer,base);

    //print converted data
    print(buffer);
}

// function to print data like printf(%d,data);
void uart::print(char* str,unsigned char data){

    int index = 0;

    // print string character by character
    while(str[index] != '\0'){

        if(str[index] == '%'){

            index++;

            if(str[index]=='d') print(data,10);

            else if(str[index] == 'b') print(data,2);

            else if(str[index] == 'x') print(data,16);

            index++;
        }
        print(str[index]);

        index++;
    }
}

unsigned char uart::read(unsigned char* string){
    // print given string
    print(string);
    // return read char
    return(read());
}

test.cpp

#include "uart.h"
int main(){
    uart.start(9600);
    uart.print("Hello world\n");
}

Now all of above function works if i write all function and declations in single .h file and don't divide my header file in .h and .cpp file. if i compile this given program i get following error.

Error

src/uart.cpp
src/uart.cpp:3:16: error: declaration of 'uart::uart()' outside of class is not definition [-fpermissive]
 uart::uart(void);
                ^
src/uart.cpp:39:6: error: prototype for 'void uart::print(unsigned char*)' does not match any in class 'uart'
 void uart::print(unsigned char* string){
      ^
In file included from src/uart.cpp:1:0:
src/uart.h:31:7: error: candidates are: void uart::print(char*, unsigned char)
  void print(char* str,unsigned char data);
       ^
src/uart.h:28:7: error:                 void uart::print(unsigned char, unsigned int)
  void print(unsigned char data,unsigned int base);
       ^
src/uart.h:25:7: error:                 void uart::print(char*)
  void print(char *string);
       ^
src/uart.cpp:30:6: error:                 void uart::print(unsigned char)
 void uart::print(unsigned char data){
      ^
src/uart.cpp:91:15: error: prototype for 'unsigned char uart::read(unsigned char*)' does not match any in class 'uart'
 unsigned char uart::read(unsigned char* string){
               ^
In file included from src/uart.cpp:1:0:
src/uart.h:34:16: error: candidates are: unsigned char uart::read(char*)
  unsigned char read(char* string);
                ^
src/uart.cpp:20:15: error:                 unsigned char uart::read()
 unsigned char uart::read(){
               ^
.build/uno/Makefile:166: recipe for target '.build/uno/src/uart.o' failed
make: *** [.build/uno/src/uart.o] Error 1
Make failed with code 2

PS:  I use inotool to compile and upload my programs to arduino and it works great. So you will find src/ in error.

Please help me. I'm stuck here.

You don't even need the constructor in the first place if it does nothing

Instead of implementing all the variations of print(), you should just subclass Print and only implement size_t write(uint8_t). This way you avoid code duplication, as there are many classes in the Arduino libraries inheriting Print.

I am making these libraries for learning purpose.i have worked with AVR microcontollers but arduino libraries amazed me.i like its code structure its very well managed.but i found one disadvantage is that memory consumption with its libs.any way thanks for suggestion.

If you solved the question, please mark the asnwer that asnwer the question or make your own answer. And edit the topic removing the [SOLVED]

uart::uart(void);

That's a prototype, not a function.  It needs a body.  Also, using "void" to say "no parameters" is really confusing.  Better to leave it out all together.
uart::uart() {
}

uart.start(9600);
uart.print("Hello world\n");

uart is a class, not an instance.  You should be using uart::start(9600) if you first set your functions to be static, or create an instance from the uart class:
uart myUart;

int main() {
    myUart.begin(9600);
    myUart.print("Hello world\n");
}

Watch your random unsigned entries...
uart.h:
unsigned char read(char* string);

uart.c:
unsigned char uart::read(unsigned char* string){

... There may be others too.

Thank you for your reply.i will correct my mistakes as you mentioned.and let me see if it works or not.

It may take a few iterations. Can't see the wood for the trees at the moment ;)  Get rid of these errors first and we'll see where we can go from there.

is it mandatory to use constructor in class,in my case uart::uart(){ }.

If you don't specify a constructor a "default" empty constructor will be provided.  It's good to be explicit and provide one thought.  You could have it all in the header file though for simplicity...  uart() {}

thank you so much @Majenko ,now my header file is working.thank you so so so much..i was stuck from past two days on this error


text:
Multiple LEDs & HC-SR04
I want to use a distance sensor like the HC-SR04 to power a stop light like parking sensor for my garage. I have seen a lot of tutorials on how to use the HC-SR04 to power a single LED and found the schematic below on how to control up to 14 LEDs by hooking them onto the 5v and using a transistor. I have added a box where I would hook the sensor in. My question is, would it work if I had the sensor hooked into the 5v as well. The plan is to have 3 sets of 14 LEDs and have one set on at any given time. I plan on using an Arduino Uno.

Thanks for all your help and encouragement. The link http://www.arduino.cc/en/Main/ArduinoBoardUno says that there is a 5 v output straight from the board's voltage regulator. Is that not separate from the output pins?

If you power your Arduino through the Vin pin, the current limit will be given by the 5 V regulator. According to it's datasheet, it's actually a power dissipation limit: the higher the Vin voltage, the lower the current limit (power = current × (Vin − 5 V)). Check the thermal pad size on your Arduino and refer to Fig. 21 (p. 8) of the datasheet.

Edgar, would I have enough current to run those LEDs and a distance sensor from the 5 v pin if I had a 9v 1A charger?

@user2969 If you hooked the power to VIN and GND, then that should be more than enough for the HC-SR04 and a handful of LEDs. On a side note, please ask another question if you have another question. Thanks!

140 mA × (9 V − 5 V) = 0.56 W. The regulator can dissipate up to 0.6 W with the minimum pad size. Then, assuming the Arduino complies with this required minimum, you should be (barely) fine.

Thanks Everyone! That answers my question. Sorry for all the confusions

If I am understanding correctly, you have 3 LEDs ... call them A, B and C (the fact that they are a group of 14 LEDs is a red herring).  As a function of the distance measured, you want ONE of LED A, B or C lit.
Since you are using an Arduino, you have GPIO pins.  Connect a different GPIO to each of A, B and C.   You can then write an application that senses the distance (as measured by the HC-SR04) and depending on the distance returned, have a set of  "if" statements which will choose which of the GPIOs to set HIGH and the others LOW.  The GPIO set HIGH will switch on the corresponding LED.
In fact, its going to look a lot like this Instructable:
http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

I think you are understanding. I was just concerned about running both the LEDs and the distance sensor off the 5v output. I didn't think it would matter as long as I always had one set of lights on so the sensor would have power

The main difference with the link you posted is the LED is being powered by the GPIO. I was under the impression that the GPIO pins wouldn't supply enough voltage (or current, I'm not sure... I really am just starting). Here is where I got the original schematic: http://electronics.stackexchange.com/questions/78096/power-14-red-leds-and-arduino-from-same-source#

The maximum amount of current through a GPIO pin is rated at 40mA.  If an LED sinks about 20mA then you can series wire 2 LEDs.  If you need to power more LEDs when a GPIO pin goes positive, then you have choices.  You can use a transistor or something like a 4050 IC (drive up to 6 higher current devices).  The maximum output current through an Arduino is 200mA ... so if you are to power everything from the Arduino, you need to ensure that you are less than this in total.

Which brings me back to the schematic above. The LEDs are powered via 5v connection, which if I have read everything correctly, can support greater current (900 mA) because it doesn't run through the Arduino

In the schematic, we see one GPIO controlling a bunch of LEDs which is not what I understand the plan to be.  The schematic also shows that the LEDs are being powered by the output 5V from the Arduino.  The Arduino spec says that it can source a max of 200mA.  Now, if you need 900mA then you connect a source that does NOT come from Arduino and give both the Arduino and the driving source a common ground.

I'm not trying to be difficult, but everything I find says the GPIO pins are current limited, but the 5 v supports more. I just double checked http://www.arduino.cc/en/Main/ArduinoBoardUno and it specifies a current limit for the 3.3 v but says nothing about the 5 v and other posts have suggested the 5 v. I am not sure how much I actually need, the LEDs in the set up above only draw about 140 mA according to the post linked. Essentially I planned on having three of those led chains each hooked up to their own transistor and GPIO pi and selecting a set based on readings from the distance sensor

Perhaps I have jumped too far into the deep end :-/

Please don't get discouraged ... the good folks on communities like this are here to help and before long, you too will be offering assistance.  Here is the official page on the specs of the Arduino.
http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
It seems to be unambiguous that the Arduino can source a total of 200mA.  This is irrespective of the voltage pin used.

Thanks for all your help and encouragement. The link http://www.arduino.cc/en/Main/ArduinoBoardUno says that there is a 5 v output straight from the board's voltage regulator. Is that not separate from the output pins?

@Kolban: The 200 mA figure you quote does not relate to the Arduino's 5 V pin: it's the maximum current the ATmega328P can sink on its Vcc pin. It's also the total current the Arduino can source on all its GPIO pins combined, plus the ATmega's own consumption.


text:
Detect my position
I'm new to Arduino, but I have this idea for a game I would like to build.
I need the Arduino to be able to determine my relative position on a straight line - 20 feet (6 meters) long.
What would be the best way to achieve that?
Priorities:

Durable (Outdoors proof)
Easy for a newbie
Cheap

EDIT. Some more context - I want to play Pong over a physical area (A grid of LEDs to act as pixels), and I want the use player's position on a line to set the position of the paddle.

Whether it's outdoor proof or not depends on the housing where you put your electronics.
For position tracking, there are basically 2 ways:
1. GPS
2. Acceleration sensors
For the given distance, a (cheap) GPS solution is not accurate enough (See https://www.sparkfun.com/tutorial/GPSTracking/clamped_edit2-L.jpg, for instance). And it may be too slow for your purpose.
Acceleration sensors also have a simple serial interface, but handling the data to get accurate results is not really easy (However I'm sure that someone has already written a public available software library)
Luckily, for position tracking on a straight line, there's another solution:
3. use a ultrasonic sensor
Maybe there are even better solutions; to evaluate, it would help if you could specify your project more detailed (how exact shall the relative position detection be? Static or dynamic calculation? If dynamic, how fast will the movement be? ...).
Edit:
It could be worth considering the following alternative:
4. Use a rotary encoder, mount it to a retractable dog leash and hook this to the player's waist. The other end of course must be mounted to a steady pillar. Perhaps this is mechanically tricky, and it limits the mobility of the players, but electrically it's very easy.

Ultrasonic would be worth trying.  It was disappointing to see your mention of Acceleration sensors in a positioning application.  I see that further in you recommend against that, but it's not a case of it "not being easy" but rather one of it just plain not working as sensors you can buy are inaccurate enough to be meaningless after double integration - and that's assuming you somehow have perfect orientation information to map acceleration axis to environment coordinates.

If it's a grid of LEDs you may be able to place pressure sensors at points up and down the grid. Then you need to step on them in order to place the paddle at that point. Doesn't sound like you need 'exact' position, just a point on a grid. And you may be able to set up such pads to step on relatively cheap: force sensitive resistors or even whip up your own w/ cardboard and thin metal (foil?) separated with foam. We did similar for a halloween prop that was activated by stepping on the doormat.


text:
Breadboard Arduino not loading sketches
I have put together a breadboard version of the arduino by following the tutorial on arduino's main website https://www.arduino.cc/en/Main/Standalone.
I have done everything exactly how that tutorial explains it and have double checked my work to ensure I didn't mess up a connection somehow. I have a usb mini breadout board that I am connecting from the breadboard to my computer and the pin outs are as follows:

GND -> Breadboard GND
5v -> Breadboard + rail
TXO -> IC pin 2
RXI -> IC pin 3
GND (GRN) -> IC pin 1 through .1μF cap

When I go to the arduino IDE and select the arduino duemilanove setting and upload a sketch I come out with this error:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

I am using a pre-bootloaded atmega328 chip and have switched it out with two others to make sure it wasn't the switch, but that didn't help either.
Any ideas on what might be the problem?

Do you have an actual USB-UART bridge or just a bare USB port?

Im using an FTDI breakout board from sparkfun
https://www.sparkfun.com/products/9716

Since you have 5V already, did you skip the power supply part?

No i still have the voltage regulator and the capacitors on the power rails

You used everything described on that page? Decoupling capacitors? The 16 MHz crystal? GND (GRN) - is not ground - hopefully you have that connected to DTR on the board (not GND). Try manually resetting the board by hitting the reset button on the breadboard, immediately after attempting the upload.

yeah, that was a typo, its not ground its DTR and yeah, everything in that tutorial, plus the .1μF cap

Your board configuration may well not match the baud rate of the boot loader (if any) allegedly present in your chip.

No need to put the italics on the "allegedly" I know it has the bootloader because pin 13 will put out a pulse when you first upload. On top of that its a part from sparkfun that is advertised to have the bootloader and the likelihood of 2 bootloaders going bad is pretty low.

To expand upon what was previously mentioned in comments, there are a number of things that need to be done before you can program an ATmega via a serial  connection:

you need to have a bootloader flashed on the chip
you need to provide a clock source (internal or external) matching the fuse settings and the rate expected by the bootloader
your programming software must use the same baud rate as the bootloader is expecting
you need to have reset the chip recently enough before starting the upload that the bootloader has not timed out - either manually or via a small capacitor to your logic level serial connection's DTR or RTS line

You commented that your chip came from Sparkfun and was sold as having a bootloader.  The programmed ATmega328p's they list claim to have the Uno's bootloader, so most likely these need to be programmed at 115200 baud like an Uno.  You instead said that you had selected the Duemilanove setting, which would mean you were trying to use a baud rate of 57600.

Make sure you have a 16Mhz crystal attached to your board at the XTAL locations properly.
If you dont have one already, connect a 0.1uf capacitor (ceramic or metal film) to the reset pin for auto reset capabilities.
The avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 issue is probably due to reset problems, where the arduino is not communicating to the computer. However, there are other possible reasons for this error. http://forum.arduino.cc/index.php?topic=28223.0
Double check that TX on the arduino is connected to Rx on the computer and Rx on the arduino is connected to Tx on the computer

If problems keep persisting, post more information so we can help you more.

Yeah, I have checked all of those, including a few solutions on the forum you recommended. Occasionally I the pin 13 light will blink while it is uploading, but its not every time and it is unpredictable. I think my 16mhz crystal might be bad or something. Im going to order a few of them and see if that helps.

Yeah, you should try that.

Do you have a picture or schematic of your design? That would help


text:
An array of existing arrays
I have a bunch of 3D arrays in the following form:
byte lines[][4][2] {
                     { {B00000000, B11110000 },
                       {B00000000, B11110000 },
                       {B00000000, B11110000 },
                       {B00000000, B11110000 } },
                     { {B11110000, B00000111 },
                       {B00000000, B11111000 },
                       {B00000000, B11111000 },
                       {B00000000, B11111000 } },
// continues for numerous elements
                    }

They are a bunch of values to push out to a pair of shift registers controlling an LED matrix. Each array is essentially an animation that plays across the LED matrix.
I would like to put my collection of arrays into an array so I can iterate through them. I know I can just combine them into one big array but the code is already opaque and I would at least like to keep separate named arrays so I can sequence and rearrange a series of animations by rearranging a series of named arrays in another array rather than one massive array of opaque binary values.
I want to do something like this
sometype* sequence[] = { lines, circles, squares } ;

or if that's not possible then:
sometype* sequence[3];
sometype[0] = lines;
sometype[1] = circles;
sometype[2] = squares;

Can I do this or some approximation thereof? If so what is "sometype"? I can't figure out how to say "an array of pointers to 3d byte arrays" or whatever it is I am trying to do. What is the syntax for deeclaring the array and dereferencing the pointers?

Try this:
byte (*sequence[])[4][2] = { lines, circles, squares } ;

Explanation: The identifiers lines, circles and squares decay
to pointers to the first element of each array. Their decayed types are
then “pointer to array of length 4 of array of length 2 of byte”. This
type could be declared as
typedef byte (*pointer_to_2d_array)[4][2];

The sequence is then an array of this type, which can be declared as
pointer_to_2d_array sequence[] = { ... };

or, if you appreciate the obscure elegance of the C syntax, as in the
beginning of this answer.

Yes, you can ( both ways )
You need
typedef byte sometype[4][2];

However, you'll probably need the size of lines, circles, etc. , which is lost by a pointer.
One way might be an end marker (A special element, indicating there are no more)
Another might be a
struct sometype {
  size_t n;
  byte [][4][2] data;
} lines ;

IMO, even 2D arrays are reaching the limits of human intelligence, and I'd prefer even more user defined types:
typedef byte Pattern[4][2]; // or a more appropriate name

Pattern lineArray[] {
             { {B00000000, B11110000 },
               {B00000000, B11110000 },
               {B00000000, B11110000 },
               {B00000000, B11110000 } }
          , { {B11110000, B00000111 },
               {B00000000, B11111000 },
               {B00000000, B11111000 },
               {B00000000, B11111000 } }
};

typedef struct {
  size_t count;
  Pattern* data;
} PatternCollection;

PatternCollection lines = {sizeof(lineArray)/sizeof(Pattern), lineArray };

PatternCollection sequence[] = {lines /* , circles, squares */ }; // if you ever need to iterate them


text:
CC3000 Wifi: Enable Debug
How do I enable debugging using Adafruit CC3000?
I am using the Adafruit_CC3000_Library.  I've followed the WebClient.ino example sketch.  I'm able to make 300 to 400 HTTP requests, but eventually the connection will hang.
I have looked at the CC3000 source and utilities and found that the Adafruit_CC3000_Library has a &Printer reference in a local variable called CC3KPrinter.  I can't figure out how to enable or activate CC3KPrinter, as it is in a code block contingent on CHECK_PRINTER.  I thought that #define-ing some variables in my sketch would help:
// None of these flags seem to enable debug within the CC3000 code.
#define _CC3000_DEBUG  1
#define DEBUG_MODE     1
#define ENABLE_CC3K_PRINTER 1

An example code snippet within the CC3000 library that I'm trying to enable is at line 916:
  CHECK_PRINTER {
    CC3KPrinter->println(F("Timed out waiting to connect"));
  }

Have you tested that the board actually connects to your wifi with more basic code? Did you put any print statement debugging into your code to see where it hangs? You're referring to this Printer section, but I feel that it is probably a red herring without knowing more about why you've picked it out. The other options look like the debugging, but if they aren't producing results then I'd just go through the library and put in print statements to see where you get to. They might not be returning anything if for some reason it doesn't get that far. Make sure your changes are correct.

@bladepanthera: I've edited the question to show that the connection works for 300-400 cycles; typically about 40 minutes.  I've confirmed via print statements that the hang happens within the CC3000 code.  This question pertains solely to enabling the CC3000 debugging code blocks.

From what I've been looking at the CC3KPrinter will print to serial when debugging is enabled, which is what you want. I'm not sure why it's not when you seem to have it enabled. I can only think of the obvious things like make sure #include "utility/debug.h isn't commented out and are you using the library you think you're using (I have two versions of Arduino on my laptop). If still no luck, then debug the library yourself with prints to find out exactly where the hang is. Make sure the buffer is clearing properly etc. Sorry can't help more.

@bladepanthera: I did re-confirm that I have the utility/debug included.  I think "debug the library yourself" is a great idea, but I'm not sure where to start.  In my Arduino IDE (v1.6.5) I can only open *.ino sketches.  The libraries are written in C++.  Are you suggesting I modify the *.cpp library files (i.e., Adafruit_CC3000.cpp)?

Yup. Literally put print statements in the cpp file.

@LookAlterno IIRC I made a new TCP connection for each request.

To enable debugging, you need to

uncomment ENABLE_CC3K_PRINTER in Adafruit_CC3000.h
If you want to pass in some debug stream other than the default Serial, you should pass a pointer to the object (which should inherit from Print, such as SD or Client) as the last argument to the constructor in your sketch:
Adafruit_CC3000(uint8_t csPin, uint8_t irqPin, uint8_t vbatPin, uint8_t spispeed = SPI_CLOCK_DIVIDER, Print* cc3kPrinter = CC3K_DEFAULT_PRINTER);

In utility/debug.h, change the value of DEBUG_MODE to 1 (or any non-zero value)

I don't know what caused your issue but you shouldn't put this in your code:
#define _CC3000_DEBUG  1

Because most of utility/debug.h is wrapped in the usual:
#ifndef _CC3000_DEBUG
.
.
.
#endif

Your #define, depending on where it's placed, could cause most of the file to be skipped by the compiler and result in compilation errors. To be on the safe side, get rid of it and simply include utility/debug.h as needed.

Poor workaround: since I was trying to solve a connection hang, I opted to use a watchdog timer solution, leveraging the lightly documented <avr/wdt.h> library.

authors: جمعان الزاهرني


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.

@Ignacio PC ints are slower

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!


text:
MPU6050 hanging/freezing
I am really short of interrupt pins on my Arduino because I have a project that already uses a lot of Arduino pins and to read DMP data from MPU6050 you always have to use an interrupt pin. I searched A LOT in the internet and many people says it's impossible to retrieve DMP data without interrupt pin. Some people also said the only way to do that would be if I could reverse engineer the MPU6050 code (which I don't know how to do).
But today, playing with MPU6050 I could finally get all of its DMP data without the interrupt pin, you just have to connect 4 pins (VCC, GND, SCL and SDA). Upload the code below to your Arduino and see that it works!
#include "MPU6050_6Axis_MotionApps20.h"
MPU6050 mpu;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorFloat gravity;
float ypr[3];

void setup() {
  Wire.begin();
  TWBR = 24;
  mpu.initialize();
  mpu.dmpInitialize();
  mpu.setXAccelOffset(-1343);
  mpu.setYAccelOffset(-1155);
  mpu.setZAccelOffset(1033);
  mpu.setXGyroOffset(19);
  mpu.setYGyroOffset(-27);
  mpu.setZGyroOffset(16);
  mpu.setDMPEnabled(true);
  packetSize = mpu.dmpGetFIFOPacketSize();
  fifoCount = mpu.getFIFOCount();

  Serial.begin(115200);
}

void loop() {
  while (fifoCount < packetSize) {
    fifoCount = mpu.getFIFOCount();
  }

  if (fifoCount == 1024) {
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
  }
  else {
    if (fifoCount % packetSize != 0) {
      mpu.resetFIFO();
    }
    else {
      while (fifoCount >= packetSize) {
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
      }

      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

      Serial.print("ypr\t");
      Serial.print(ypr[0] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[1] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[2] * 180 / PI);
      Serial.println();
    }
  }
}

There is only one problem: Intermittently the Arduino hangs in the getFIFOBytes function for no reason. I am pretty sure it's a bug because when you call too many times getFIFOBytes for some reason the Arduino freezes.

Actually, removing the interrupt completly solves it all!

I added a mpu.resetfifo after de mpu.dmpGet.... lines.
Since then 2 different systems work for at least 5 hours and with the original interupt pin attached


text:
Sound sensor signals with time bracket
I've tried many codes for this to work but anything isn't helping at all, so my code should work like this: If a sound sensor (3 pins, A2) sends 5 signals into the Arduino within 10 seconds (the time gap of every signal varies, but doesn't matter as long as it sends 5 signals), the LED (13) will light up. This is my recent code if it could help
int led=13;
int sensor=A2;

void setup()
{
   pinMode(led, OUTPUT);
    pinMode(sensor, INPUT);
    Serial.begin(9600);
}

void loop()
{
    unsigned long StartMillis = millis();
    unsigned long CurrentMillis = millis();
    int signal_count=digitalRead(sensor);
    int signal_limit=5;
    Serial.println(signal_count);

    while ((CurrentMillis - StartMillis)==5000)
    if (digitalRead(sensor)=0)
    {     signal_count ++;
        Serial.println(signal_count);
    }
    if (signal_count>signal_limit) {
        digitalWrite(led, HIGH);
    }
    else {
    digitalWrite(led,LOW);
    }
}

think about the first two program lines inside the loop() block .... what do they do?

What sound sensor are you using? Is its output analog or digital? And what do you mean by "signal"? What counts as a "signal" for you?

I'm using digital sound detector sensor module. I don't know but it prolly uses analog (that's what I got from website references). The signal I referred to is the signal sent by the sound sensor to the arduino (HIGH or LOW)

Still you didn't explain what a "signal" is. Does it mean, that the sensor should go high and then low ( a pulse)? Or how do you want to count "signals"?

I just wanted to count the HIGH signals, then use the number of signals recieved in a short amount of time to trigger a led to light up

Your handling of millis() is wrong. With these two lines:
unsigned long StartMillis = millis();
unsigned long CurrentMillis = millis();

StartMillis will always have the same value as CurrentMillis. (Ok, I guess its possible for millis() to return a value that's increased by 1 the second time it's called, but that is extremely unlikely. The 2 lines takes much less than a millisecond to execute.)
Your
while ((CurrentMillis - StartMillis)==5000)

will never evaluate to true, so the code in the while block will never execute.
This if statement is also wrong:
if (digitalRead(sensor)=0)

You want == (comparison) not = assignment. I'm surprised the compiler even allowed that to compile, since you are trying to set the function digitalRead(sensor) to 0, which doesn't make sense.
Change that code to read:
if (digitalRead(sensor)==0)

(Assuming you want the body of the if statement to execute when your sensor value is 0.)


text:
Weird behavior of variables when replacing for loops with if statement
See the picture of serial monitor showing I get a large number, 4 billion, when I multiply two called functions together. It always happens after 53 if I change the amount the if statement counts to. I serial monitored the if statement and it counts to 600 then down then up and repeats good and the sensorValue stays the same.  I get rid of the division in y and I put it all in the for loop and still get a large number. My purpose is to fade pin and adjusts analogWrite at same time. It adjusts but does not fade. Does replacing for loop with if statement or calling to many functions create a bug.

int analogInPin = A0;
int analogOutPin3 = 3;

int sensorValue;

int i = 0;
int a;
int y;

void sens(int &sensorValue){
  sensorValue = (((long)analogRead(analogInPin)*255)/1023);
}

void inOut(int &i){
  if (i > -1){
    i = i + a;
  if (i == 0){
     a = 1;
  }
  if (i == 600){
    a = -1;
  }
  return i;
 }
}

void updateFade(){
  sens(sensorValue);
  inOut(i);
  unsigned long y = ((sensorValue*i)/600);
  Serial.println(sensorValue);
}

void setup() {
  Serial.begin(9600);
  pinMode(analogInPin,INPUT);
  pinMode(3,OUTPUT);
}

void loop() {
  updateFade();
  delay(100);
  analogWrite(3, y);
}

Signed into unsigned doesn't go. If i is -1 then what is y going to be?

y will always be 0 because the one calculated inside that function is local to it and dies when the function ends without having ever been used.  So the y that is used int he analogWrite in loop will always be 0.

If I can make another unrelated suggestion, your sens function doesn't need to take any parameters.  It could just be sens().  Since sensorValue is global, you can modify it and access it from anywhere in the program.  You don't need to pass it around as an argument.  You only need the whole pass by reference thing if you are trying to modify local variables in one function from another function.  But that's not what you're doing here.  You've got a global variable.  Same thing with your inOut function.  i is global, so you can just use it.  You don't need to pass it around.

these are all the same integer .... binary 1111 1111 1111 1111 1111 1111 1100 1010 == hexadecimal FFFFFFCA  == unsigned decimal 4294967242 == signed decimal -54

You define i,y,i as global variables so there is no need to hand them over to different functions. They can be accessed and changed in all parts of your program.
define instead of
int y;

change to
long y;

and change
 void inOut(int &i){

to
void inOut(){

and remove
   return i;// Its a global var

change the line
unsigned long y = ((sensorValue*i)/600);

to
y = ((sensorValue*i)/600);

Try to avoid the same names for global and local vars. It might happen that the compiler handles it as a redefinition, which might lead to all sort of trouble in complex programs. (Also for you if you look onto an ill documented code some months later)And get rid of the delay it stops processing (also your subroutines) see Blinkwithoutdelay how to do it properly ArduinoIDE->file->examples->2 Digital->Blinkwithoutdelay

Thanks for the help, this is my working code.  I changed things to long, got rid of some long's, stopped passing variables, and forced number in sensorValue to be long.  It now counts up and down were I set the potentiometer every minute.

int analogInPin = A0;
int analogOutPin3 = 3;

long sensorValue;

int i = 0;
int a;
long y;

void sens(){
  sensorValue = ((analogRead(analogInPin)*255L)/1023); //force 255 to be long
}

void inOut(){
  if (i > -1){
    i = i + a;
  if (i == 0){
     a = 1;
  }
  if (i == 600){
    a = -1;
  }
 }
}

void updateFade(){
  sens();
  inOut();
  y = ((sensorValue*i)/600);
  Serial.println(y);
}

void setup() {
  Serial.begin(9600);
  pinMode(analogInPin,INPUT);
  pinMode(3,OUTPUT);
}

void loop() {
  updateFade();
  delay(100);
  analogWrite(3, y);
}