text:
Have I bricked my Arduino Uno? Problems with uploading to board
I can't upload sketches to my Arduino Uno.

Have I "bricked" it?
What steps can I take to work out what is wrong?
What can I do to fix it?

For those wondering, this isn't an actual question!
It's more of a reference question. The question itself is made quite broad on purpose. The answer however is greatly detailed and so can this question be used as a reference.

It's more of a reference question. Quite correct. See It's OK to Ask and Answer Your Own Questions.

@Nick_Gammon Yes. But I feel that you somehow should have noted it somewhere. At first sight I was (slightly) annoyed by the fact that the question was so broad and it seemed that you didn't have done any research. But when I saw your answer, it all made sense.
Also, (when you can) you shouldn't forget to accept your own answer, so that others who are trying to help don't start answering, looking into or commenting questions on this (which wouldn't really help you, as you did already find a rather good way to debug this problem).

Thanks for the feedback. I initially thought to post the question with a note that I was going to post my own answer, but then I saw the checkbox about "answer your own question" so I ticked that instead. As for accepting it, I'm not allowed to for 20 hours. It seemed a bit odd to me to accept your own answer, but certainly I can do that when I am permitted to. I asked a question on Meta Arduino What is a canonical question, exactly? to try to work out the correct procedure but got no responses.

@FuaZe and Nick Gammon: This seems great in general, the only suggestion I'd make would be to make the subject more suggestive of what the question and answer are really about. As it is, I think I might have been tempted to blow it off as too vague. Perhaps the title could be "How can I troubleshoot failed uploads?"

What do others think? "Troubleshoot failed uploads" sounds a bit bland to me. On the Arduino forum we often get people wondering if they have "bricked" their Arduino in the thread title, rather than the (possibly more accurate) title: "I am having trouble uploading".

Amended title to include "problems with uploading" in it.

I know this is an old question, but maybe you can still help me...I've been following your troubleshooting procedure since I can't get any sketches to upload to my board, and got as far as the loopback test. When I try to do open Serial Monitor, however, I get the error "Error opening serial port 'COM2'. (Port busy)" even though COM2 should be the correct port. Any suggestions?

Just solved it thanks to help on the Arduino forums; turns out this is a bug in the 1.6.8 version of the Arduino IDE, and reverting to 1.6.7 solved the problem right away.

Also try the product page FAQs.  My Arduino MKR Zero, wasn't a recognised usb device, and required a double pressing the reset button while plugged into my PC.

It probably isn't bricked
I've got quite a few Arduinos, and over the last few years have only ever "bricked" one, and I think that was by zapping it with static electricity. Unfortunately that particular one had a SMD (surface mounted) processor chip, so it isn't easy to try swapping it with another chip.
Stay calm, and try the following steps ...

Example board
An "Arduino Uno" is not just one thing that might fail. It has multiple major components, and possibly only one has failed (if any). See this reference photograph:

Major components are:

Atmega16U2 processor - this handles the interface to the USB connection
Atmega328P processor - this is the "main" processor which has your sketch on it
Voltage regulator - this converts incoming power from the power jack to 5 V
Power LED (green) - marked "On"
Indicator LED (yellow) marked "L" - connected via an op-amp to digital pin 13
Rx and Tx LEDs (yellow) - these indicate if the USB chip (Atmega16U2) is receiving or transmitting

Note that the Rx and Tx LEDs are not connected directly to digital pins 0 and 1 on the board (marked Rx and Tx). They only illuminate if you are doing serial communications via USB, not if you have something (like a GPS) plugged directly into digital pins 0 and 1.
Also note that since the "L" LED is connected via an op-amp, it may illuminate if pin 13 is set to an input in your sketch. This is normal. It doesn't mean that something is erroneously sending data.

Check the power
USB power

Plug the board into your computer with the USB cable and check that the green "On" LED lights up.
Use a multimeter and a couple of jumper leads to test between the 5V pin and the GND pin (arrowed at the bottom). You should get a reading of around 5.0 V (I got 5.04 V on mine).

(You can buy a cheap multimeter for around $10 if you don't have one, but you are better off getting a better one for around $50 - check all the electronics web sites and stores.)

Also test between the 3.3 V pin and the GND pin - you should get 3.3 V.

If you do not get 5 V with the USB cable plugged in make sure the other end is connected to your computer. Also try a different cable.
Power jack

If you are using, or planning to use, the power jack (marked "power in" on the photo) disconnect the USB, and plug in a power supply - which should be 7 to 12 V DC with positive on the center pin.
Measure the 5 V and 3.3 V pins as above. You should still see the same voltages on them.

If you get 5 V with the USB connected, but not with the power supply then the voltage regulator (marked on the photo) is probably damaged. Or, possibly the power supply has failed. Try a different power supply to confirm which it is.

Check the power-on LED flash
If you have the Optiboot bootloader (the Uno normally ships with that) then if you press and release the Reset button, or unplug and plug the USB or power cable back in, the "L" LED should flash quickly 3 times. The "on" and "off" times are 50 ms each, the three flashes should be over within about 1/3 of a second.
If it doesn't, you may have a problem with the bootloader, or the main processor chip (Atmega328P).

Try uploading a sketch
Important: If you are having trouble uploading sketches remove any connected devices (like shields). Also remove jumper wires plugged into the board sockets. In particular, there should be nothing plugged into digital pins 0 and 1 (Rx and Tx) because that will interfere with communicating with the uploading computer.
Choose one of the simple example sketches (eg. Blink) and try to upload it. This is what you should see:

The "L" LED should flash 3 times. This is because the main chip is being reset by a command from the uploading process.
The "Rx" LED should flash quickly. This is the instructions from the uploading process trying to activate the bootloader.
The "Tx" LED should flash quickly. This is the processor acknowledging the uploaded data.

You may see the above, even if the uploading process fails. This could be because the wrong board type is selected.
If only the "Rx" LED flashes, it could be because of a problem with the bootloader, or the main processor chip (Atmega328P). Someone is knocking, but no-one is at home!
Check the board type
If the LEDs flash, but you get a message like this:
avrdude: stk500_recv(): programmer is not responding

Check the board type:

If you have the wrong board type selected it will probably send the wrong uploading instructions, and time-out or otherwise fail. If you are like me and have different boards lying around it is easy to forget that the last upload you did was for a different board type.
Check the comm port
If the LEDs don't flash at all, you may have the wrong comm port selected.
Check the comm port:

Try a different PC / Mac if possible
Try your Arduino on a different PC/Mac if you have one to hand. This can narrow down whether or not you have an issue with the particular computer you have plugged it into, or computers in general.
Do a loopback test

Disconnect all shields and other wires
Remove the board from the power
Connect a jumper wire from RESET to GND (orange wire in photo)
Connect a jumper wire from Rx to Tx (white wire in photo)

Wiring:

Plug in the USB cable, and start up a terminal program - such as the Terminal Monitor in the Arduino IDE. Type something and send it (eg. hit Enter in the Terminal Monitor).
Everything you type should be echoed back.

If everything is echoed back: That confirms you have the right comm port, the USB cable is OK and the USB interface chip (Atmega16U2) is probably OK.
If nothing is echoed back, check:

You have the correct comm port.
Try a different cable. Some cheap USB cables only have power wires and not data wires.
Check the device driver for the Arduino is installed. You probably don't need to do this if that board worked previously on this computer, but it can be worth doing if this is the first time you plugged this board into this computer.

Test the Atmega16U2 chip
If your board fails the loop-back test, and you are certain the USB cable is OK, then you can test the Atmega16U2 chip itself. There is an ICSP (In Circuit Serial Programming) header on the board, adjacent to the Atmega16U2 chip, and near the USB socket.
Disconnect the power first (unplug the USB cable and any power cable).
Then you can connect the ICSP header via 6 jumper wires to a known good Uno, as shown in the photo:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the Atmega16U2 chip is marked with a small white dot, near the "F" in "AREF". Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".
Connect up:
Good board         Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

Double-check your wiring.
Then on the "known good" board install the "Atmega_Board_Detector" sketch as described on the Atmega bootloader programmer page. The code is at GitHub - nickgammon/arduino_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Detector".
Once installed, open the serial monitor, set it to 115200 baud, and you should see something like this:
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x94 0x89
Processor = ATmega16U2
Flash memory size = 16384 bytes.
LFuse = 0xEF
HFuse = 0xD9
EFuse = 0xF4
Lock byte = 0xCF
Clock calibration = 0x51
Bootloader in use: No
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 4096 bytes starting at 3000

Bootloader:

3000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
3010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
3020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xEE 0xC4 0x00 0x00
...
3FE0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
3FF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

MD5 sum of bootloader = 0xD8 0x8C 0x70 0x6D 0xFE 0x1F 0xDC 0x38 0x82 0x1E 0xCE 0xAE 0x23 0xB2 0xE6 0xE7
Bootloader name: Arduino-dfu-usbserial-atmega16u2-Uno-Rev3

First 256 bytes of program memory:

0: 0x90 0xC0 0x00 0x00 0xA9 0xC0 0x00 0x00 0xA7 0xC0 0x00 0x00 0xA5 0xC0 0x00 0x00
10: 0xA3 0xC0 0x00 0x00 0xA1 0xC0 0x00 0x00 0x9F 0xC0 0x00 0x00 0x9D 0xC0 0x00 0x00
20: 0x9B 0xC0 0x00 0x00 0x99 0xC0 0x00 0x00 0x97 0xC0 0x00 0x00 0x48 0xC4 0x00 0x00
30: 0x0C 0xC4 0x00 0x00 0x91 0xC0 0x00 0x00 0x8F 0xC0 0x00 0x00 0x8D 0xC0 0x00 0x00
...

However if you get a message like this:
"Failed to enter programming mode. Double-check wiring!"

That would appear to indicate that your ATmega16U2 is not working.

Test the ATmega328P chip
Disconnect the power from the "known good" Arduino Uno and rewire the ICSP jumpers as per this photo, to connect them to the "main" processor on your Uno:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".
The wiring is the same as before, except you are connecting to the other ICSP header - the one at the end of the board, furthest from the USB socket.
Good board       Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

Once connected, open the serial monitor, set it to 115200 baud, and you should see something like this:
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
...

MD5 sum of bootloader = 0xFB 0xF4 0x9B 0x7B 0x59 0x73 0x7F 0x65 0xE8 0xD0 0xF8 0xA5 0x08 0x12 0xE7 0x9F
Bootloader name: optiboot_atmega328

First 256 bytes of program memory:

0: 0x0C 0x94 0x35 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
10: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
20: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
30: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
...

In this case it confirms that the main processor is working, and has the Optiboot bootloader on it.

Things you can fix
Failed voltage regulator
This isn't easy to replace, but it is only needed if you use the power jack. If you run from USB then it is not required. Alternatively you could arrange for a 4 to 5 V supply (eg. 3 x AA batteries) and connect them to the 5 V socket on the board directly.

Failed ATmega16U2 chip
This is only required for uploading sketches via the USB port, and serial debugging. It isn't particularly easy to replace because it is a SMD (surface mounted device). However you can manage without it.
You can upload sketches via the ICSP header, if you purchase a ICSP programming device.
Examples of such devices plugged into the ICSP socket:

(Those photos were taken of a Ruggeduino, but the concept is the same).

You can also get an FTDI cable, like this:

Connect it to your board's serial ports like this:

FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

Now you can upload sketches directly to the main processor, bypassing the USB chip.

You can also use my Atmega chip stand-alone programmer to upload .hex files - this lets you copy the .hex file for a sketch onto an SD card, and then program the board via the ICSP header.

Failed ATmega328P chip
The main processor can be replaced fairly easily if it is mounted in a socket. Get a replacement chip from somewhere like Adafruit for around $US 6. Alternatively, try eBay. Try to get a chip which has the Optiboot bootloader already on it, to save hassle.
Carefully prise the existing chip out of the socket, and install the new one, taking note of the location of pin 1. Pin 1 has a notch on the chip, and its correct orientation is noted on the first photo in this post with a yellow dot (closest to the edge of the board). You will probably need to straighten the legs slightly. Hold the chip by the ends and gently push down onto a flat surface, like a desk, until the are pushed inwards a bit. Try to not touch the metal pins, you may zap them with static electricity.

ATmega328P responds but has no bootloader
I have a sketch at Atmega bootloader programmer which will replace the Optiboot bootloader. The wiring is the same as for the chip detector sketch. The code is at GitHub - nickgammon/arduino_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Programmer".
Install the sketch on your "known good" Uno, and connect it to the target board with the wiring shown earlier.

Open the Serial Monitor on your "good" Uno and you should see this:
Atmega chip programmer.
Written by Nick Gammon.
Version 1.35
Compiled on Jul  9 2015 at 15:06:58 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...

Type "U" for the Uno (Optiboot) loader.
Using Uno Optiboot 16 MHz loader.
Bootloader address = 0x7E00
Bootloader length = 512 bytes.
Type 'Q' to quit, 'V' to verify, or 'G' to program the chip with the bootloader ...

Type "G" to program the chip.
You should see:
Erasing chip ...
Writing bootloader ...
Committing page starting at 0x7E00
Committing page starting at 0x7E80
Committing page starting at 0x7F00
Committing page starting at 0x7F80
Written.
Verifying ...
No errors found.
Writing fuses ...
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Done.
Programming mode off.
Type 'C' when ready to continue with another chip ...

This takes about one second. Now the bootloader is installed.

Watchdog timer problems
The watchdog timer (off by default) can be configured to reset the processor after a certain time. The intention is to recover from a "hang" for a processor deployed in the field. However if the timer is set for a short period (like 16 ms) then the processor can reset again before the bootloader has a chance to do anything.
The symptoms are that you cannot upload any new sketches. Some modern bootloaders (like Optiboot) take steps to stop this problem as one of the first things they do. However others do not.
This can be difficult to recover from, because once the sketch runs, you have the problem of it resetting, and if you have the problem you can't replace the sketch. People often report that they have to burn a new bootloader to recover. However that is only because, as a side-effect, burning a bootloader erases the current sketch.
There is a way of recovering. Take these steps:

Power off the board completely (remove the USB cable).
Hold down the Reset button, and keep it held down (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting, and thus activating the watchdog timer
Still holding down Reset, reconnect the USB cable.
Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).
It should now upload OK - as the sketch which activated the watchdog timer never started.

Problems with the Mega2560 upload
I mention this here, even though this post is really targetting the Uno board, because it is quite common.
Some versions of the Mega2560 bootloader look for "!!!" in the incoming upload from the PC, and if they see that, drop into debugging mode. This causes the upload to fail.
Example code:
Serial.println ("Furnace overheating!!!");

Solutions:

Install a more recent bootloader. My "bootloader uploader" sketch mentioned earlier in this reply should install a bootloader that does not have that issue.

Or (more simply):

Do not use "!!!" in your sketch.

Problems uploading to the Leonardo / Micro / Esplora etc.
Boards with the ATmega32u4 as their main (and only) processor can be trickier to upload to. This is because the same chip has to handle uploads and also run your code.
There is a small window of opportunity, after the board is reset, when it looks for a new sketch to be uploaded. The technique for uploading to these boards is:

Compile your sketch without errors.
Start the upload
As soon as the IDE reports "Uploading" press and release the Reset button.

You only have a second or so to do this, before the old sketch starts running. Don't be discouraged if you have to repeat this process a couple of times. That is normal.

References

Solving problems with uploading programs to your Arduino
Sketch to detect Atmega chip types
GitHub site with chip detector / bootloader programmer
Atmega bootloader programmer
Atmega chip stand-alone programmer to upload .hex files
Engbedded Atmel AVR® Fuse Calculator
Arduino Uno Rev3 pinouts photo

Wow. This is a great great great answer

That is a wonderful answer sir.

"If you get 5 V with the USB connected, but not with the power supply then the voltage regulator (marked on the photo) is probably damaged. Or, possibly the power supply has failed. Try a different power supply to confirm which it is." - why would this prevent you from uploading sketches?

You are quite right, it wouldn't. However the check-list was supposed to be a general check-list for failures. In this case it would be more like "I can upload a sketch, but when deployed in the field, with a power supply (wall-wart) it doesn't work".

I recently had a problem with the new FTDI drivers that "brick" chinese "FTDI compatible" (well you could say imitation) chips. They put the PID of the device to 0x0000, which will make the drivers invalid. You can choose to change the PID back with the M_PROG tool on FTDI or to change the drivers (and set up windows to allow unverified drivers).

I thought consumer outrage caused them to stop doing that?

@Nick Gammon I would have put after  "Check the comm port" to plug in the arduino on another computer running arduino IDE if that possible. If the arduino is detected and works on another different PC than it still ok. That may save time - if you have multiple PCs or can borrow one- rather than go through your long answer.

Good idea. I added that.

Excellent work, @Gammon. You answered a lot of questions I had not thought to ask. As for bricking boards, the only way I have done that is by having a Nano installed out at my solar panels inside a white box where the outside air temperature got above 100 F. That one never came back. But otherwise, the Nano seems to be very tolerant. So, I now have a small fan that turns on when the box's internal DHT-22 temp is above about 90. Haven't lost another board since.

What do you mean here "Note that the Rx and Tx LEDs are not connected directly to digital pins 0 and 1 on the board (marked Rx and Tx). They only illuminate if you are doing serial communications via USB, not if you have something (like a GPS) plugged directly into digital pins 0 and 1."? I have gsm/gps module connected to RX0 and RX1. It was working with module connected to arduino too, but once arduino command line start throwing:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
Errors

I suggest you post that as a new question. Comments under answers are not really intended for a question/answer session.

Fantastic answer, couldn't be more complete.

I tried the loopback test with my Arduino Nano. The TX/RX leds blink but nothing is printed in the serial monitor. Can you help me with that? Also I cannot upload anything.

About the "Problems uploading to the Leonardo / Micro / Esplora etc." part: I blocked an Arduino Micro by stupidly having a sketch calling cli() without matching sei(), which causes an "USB device not recognized" on the PC when connecting the USB port. The easiest way to recover the board in this situation is to connect an external programmer using ICSP and to re-burn the bootloader (which will erase the sketch). It probably also work to just upload a new sketch using the external programmer but I didn't try.

@LeFauve Did you try my suggestion of holding down Reset towards the end of my post?

@NickGammon Yes, I tried this first but there is less than one second between the moment I release the reset and the moment I get the "USB device not recognized" message. At this point, the Arduino IDE don't even see an Arduino on any port so it cannot upload anything to it.

At least - as I assume you upload your sketch via avrdude - please give more information about the upload failure (e.g. output of sketch uploader) so people here can help you better.
Additionally to the great answer of Nick Gammon, please search for exclamation marks in your sketch. If your sketch contains a string with more than or equal to 3 exclamation marks, the upload will fail, as old versions of the Arduino Bootloader will interpret these exclamation marks as another function and the upload will stop.
An example for stopping the upload:
char* test = "This will stop the upload!!!";

See Google Code issue.

Good point. This applies mainly to the Mega2560, but I admit I omitted that. :)

Added a section to deal with this issue.

I have bricked 2x ATMega328P on my Arduino Uno board due to static (I think).
The static seems to have killed the TX pin and hence the program can't be downloaded using the USB cable.
The easiest solution is to replace the microcontroller. You can buy a new ATMega328P DIP programmed with the Arduino bootloader (such as this one from Adafruit) and you are ready to go again.
Alternatively, you can still program the ATMega328P's by using the Atmel Ice or AVRISPmkII programmer or by using another Arduino as an ICSP programmer. When you do, all but the Tx pin work fine.


text:
XBee on Arduino Fio - how to read the status of a local digital XBee output pin?
I am using a Fio to control a set of relays. The unit uses an XBee (series 1 Pro) in transparent mode to receive commands over serial UART and everything works fine. The XBee is also configured for digital Input/Output Line Passing and the XBee on the Fio "mirrors" on an output pin the input state on a remote XBee and also this works fine.
How can I interrogate from the Fio the state of the output pin (e.g. D0) of the local (receiving) XBee? Is there an AT command that I could send via Serial.println("ATxx") that would trigger the XBee to send back over UART the status of the pin (high or low)?

You cannot read the state of output pins via an AT command, you can only read the state of input pins using the ATIS command.
See: http://ftp1.digi.com/support/documentation/90000982_S.pdf

source: Stack Exchange

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

sort: votes


text:
How to use C Libraries for Arduino code
I have a code in Visual studio that I want to implement in Arduino. But
there is a problem. Many libraries usable in Visual Studio aren't usable
in the Arduino IDE. How can I use them in my Arduino code? To be
precise, the libraries I want to use are
#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <math.h>
#include <ctime>

I know I have <iostream> available in Arduino. <math.h> is also
available I think along with the <string> library. The main problem is
to how to use #include<queue> and its functions such as
priority_queue() and other functions of iosteam like .pop()? Any
help would be highly appreciated.

Weird, I can remember using the same ATMega328P with another compiler, where it did work.
Though you can check if an external library fits your needs: http://playground.arduino.cc/Code/QueueList
But I would understand if you prefer a solution rather than a work-around?

The Arduino doesn't have an operating system, so therefore doesn't have a C standard library.

@mypal125: The Arduino does have a standard C library (avr-libc for the AVR based boards). What it lacks is the C++ STL, but see Nick Gammon's answer on how to add it.

@EdgarBonet: TIL!

Some of the libraries you mention (iomanip, iostream, queue, string) are part of the STL - Standard Template Library. Whilst it does not ship with the IDE download, you can install it yourself. See The Standard Template Library (STL) for AVR with C++ streams - a port to the Arduino by Andy Brown.
I have some implementation notes here.
Be aware that a lot of Arduinos don't have much RAM, so you need to use libraries like this with caution.
Library download: AVR standard template library, version 1.1.1 - 197.29 kB

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


text:
Inappropriate ioctl for device
I am using an Arduino Uno and a Mac and trying to upload my code into the board.
I tried uploading the program from different computers(MacBook Air and Pro) and I still have this problem.
How do I fix this? I tried downloading the FTDI driver. I went to the website that they suggested and tried following the instructions. I even followed other posts in Stack Exchange but I still cannot upload the code.
EDIT
Programmer -> AVRISP mkll
I am using a cable to connect to my Mac and I am using the Arduino software. The cable connected between the Arduino USB and Mac USB port.
I tried quitting and relaunching Arduino app. Once it launches I just press the upload button while my USB is plugged in. My available ports in the app are /dev/cu.Bluetooth-Incoming-Port and /dev/cu.Bluetooth-Modem
And this is the error
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

Please edit question and add following info:  How the Uno is connected to Mac, including name or model number of cable or whatever, and what connects where.  The program you used and the commands you entered to upload the code.  If you are using arduino ide, what options you selected, eg which port, which programmer, programming mode.  URL of "the website they suggested".

Better, but please add the other info requested.  The problem will be something simple but if people don't know what you have or what you did, then their answers are just guesses.  What options did you set?  What buttons did you click? What's selected at Tools/Port ? at Tools/Board ? What is each end of the programming cable plugged into? What's the cable? (Eg say if it is a USB A to USB B micro, connected to a USB port on Mac and USB on Uno)

Tried running your arduino as a root user?

yes. But i have the same error

Your question is unclear.  Are you trying to program the Uno through the Uno's on-board USB interface, or are you trying to program it through a hardware programmer?

i don't get you. Sorry i am just a beginner

I think @Majenko is asking if you are using a plain USB cable vs some add-on programmer board.  From your latest edit, I assume you use a plain USB cable.  I don't know much Mac stuff but it looks to me like port setting is wrong – Bluetooth is totally not relevant to this USB cabled connection.  See Getting Started w/ Arduino on Mac OS X which says to use a port like /dev/tty.usbmodem or  /dev/tty.usbserial

Also see Mac OS X usbmodem ports missing?, a lengthy discussion of ins and outs of getting  usbmodem ports to show up on Mac

Thank you very much for the excellent explanation. It was a breeze to fix the problem with such a clear description of what to do!

Did any of the answer help you to resolve your issue? If so, could you mark the answer that helped you the most as "accepted"?

I solved the same problem by simply following the first person's advice to try a different USB cable. He was right!

Plug your Uno into the Mac using a known good USB cable.
Go to the Apple menu -> About This Mac -> More Info -> System Report
Under the USB selection (on the left) please confirm whether or not you see something like this:

You can also open a Terminal window and type:
system_profiler SPUSBDataType

Amongst other things you should see:
USB:

    USB High-Speed Bus:

      Host Controller Location: Built-in USB
      Host Controller Driver: AppleUSBEHCI
      PCI Device ID: 0x3b34
      PCI Revision ID: 0x0006
      PCI Vendor ID: 0x8086
      Bus Number: 0xfd

        Hub:

          Product ID: 0x2514
          Vendor ID: 0x0424  (SMSC)
          Version: 0.03
          Speed: Up to 480 Mb/sec
          Location ID: 0xfd100000 / 2
          Current Available (mA): 500
          Current Required (mA): 2

            Communication Device:

              Product ID: 0x0043
              Vendor ID: 0x2341
              Version: 0.01
              Serial Number: 9314036423335121A0B1
              Speed: Up to 12 Mb/sec
              Manufacturer: Arduino (www.arduino.cc)
              Location ID: 0xfd130000 / 8
              Current Available (mA): 500
              Current Required (mA): 100

Note the "www.arduino.cc" entry.
In your Arduino IDE you should see the Arduino as a tty.usbmodemfd131 (or some similar number).

If you see all that it should work.
If not, please state in what way it differs.

Programmer -> AVRISP mkll

The Tools > Programmer menu selection is only used when you do Tools > Burn Bootloader or "Upload Using Programmer. It is completely ignored when doing a standard "Upload". You should be doing an "Upload" (Command-U) not an "Upload using programmer" (Shift+Command+U). So it makes absolutely no difference what you select from the Tools > Programmer menu.

I solved this problem.  Maybe this post will help others.
I've come across this problem a couple of times.  I literally searched for hours for the answer and ended up using several suggestions.
Both scenarios I solved are documented below as 'Scenario A' and 'Scenario B':
======================
Scenario A
Plugged in a new Arduino Uno R3 board, successfully compiled the standard "Blink" sketch.  When I tried to upload it to the board, I got this message:
Sketch uses 1,066 bytes (3%) of program storage space. Maximum is 32,256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes. avrdude: ser_open(): can't open device "COM1": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
The Port Options in the IDE (Tools--> Port) only showed  /dev/cu.incoming-bluetooth-port
Here's what worked:

Downloaded and Installed the CH340 driver
Removed the FTDI drivers from my mac.  Apple recently installed a new utility that prevents removal of what it considers to be critical components.

The process that enforces this rule is called csrutil.
You'll have to disable this process to remove the FTDI driver.  Then you'll need to re-enable it when you are done.  This required a restart in recovery mode.  Here's how to do that:
a.)  power off the mac then hold 'command'+R during the restart until the image of the apple appears.
b.)  when the screen refreshes, click on 'Utilities' menu then 'Terminal.
c.)  type csrutil disable
d.)  Hit enter
e.)  Restart  [Note:  You may be able to execute the next two commands in the terminal before restarting.  I just didn't test it that way.  If the system will allow you to, then by all means run all three commands one after the other THEN restart and you should be on your way.]

remove the FTDI drivers by opening the terminal program again and entering the following command:
   sudo rm -R /System/Library/Extensions/AppleUSBFTDI.kext

Type in your password when prompted.

Restore the apple csrutil by following steps a and b above.  Task c will be the same EXCEPT you'll type this instead:
csrutil enable

Then follow steps d and e.

When you restart the arduino IDE, you should see a more comprehensive list of ports besides just the bluetooth port.
======================
Scenario B
This board was an import and clearly not an original Arduino/Genuino.  Attempts to load sketches resulted in this lovely error:
    Using Port                    : /dev/cu.usbmodem1421
    Using Programmer              : arduino
    Overriding Baud Rate          : 115200

avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
There was only one Port listed in the IDE, dev/cu.Bluetooth-Incoming-Port.
It had been a while since Scenario A had occurred and since then I'd installed a few OS updates.  Checked the drivers and low and behold, the darned FTDI drivers had RETURNED!!
I repeated the steps in scenario A above but the problem remained.
Then I installed an updated board configuration from arduino and it worked!  Testing on the first board I'd used under scenario A were successful as well.  Here's what I did:

In the IDE go to Tools-> Boards -> Boards Manager
I installed 'Arduino SAM Boards (32-bits ARM Cortex-M3) by Arduino version 1.6.8
Unplugged and replugged the USB cable into my arduino.
In the IDE go to Tools -> Port.  The /dev/cu.usbmodem1421 was listed as a port option.  Selected that.
Uploaded my sketch.
Bask in glory of SUCCESS!

I hope this was helpful to you.  I spent two days on Scenario A and 3 hours on Scenario B.

Warning to future testers, after installing that driver whenever I plug my arduino it freezes my mac and I have to restart

I've also had this error message when I've left another serial terminal connected to the same port the Arduino IDE is trying to use.

I got this error on my Macintosh system and the problem was that I needed to choose the correct port on the USB. Somehow it had auto-connected to a Bluetooth port which was listed under Tools->Port as /dev/cu.Bluetooth-modem and was my daughter's cell phone. I chose a port labeled /dev/cu/wchusbserialfd... and it worked fine.

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


text:
Write to file in SD card in wave shield V3
I just started tinkering with Arduino. I'm curious to know though, is it possible to read and write to a file stored in the SD card in the Wave shield v3 by Elechouse? I'm able to play files stored in said SD card, but I don't know how I'd go about writing some logs. I'm using an Arduino Mega.
Thanks in advance.

No, you cannot.  The shield is basically a cheap WAV or AD4 (whatever THAT is) playing chip which loads the audio data direct from an (old, small) SD card.  The only control you have is IO pins that emulate pressing the buttons on an MP3 player.


text:
Choose the correct solar panel and battery for solar use
I am planning to build a weather station powered by solar power. I want to use an Arduino Nano because it's low power requirement. I want to connect some basic sensors to it (temperature, humidity…) as well as an anemometer, a wind vane and a rain gauge. The weather data should be sent wireless via 433 mhz to a raspberry pi, which acts as a web server. I do not have power cable access to the Arduino so solar is the only option.
Which solar panel should I use? I was planning to use 2 2.5W 5.5V panels which charge a Lithium-Ion battery which powers the Arduino using a step up converter. Assuming I have 2-4h of direct sunlight per day and I want to query the sensors every 5 minutes, how big of a battery should i choose? I don't want it to go out of power and want it to last a couple of days without sun.

How large is the load?

I don't know. I heard the Arduino nano draws very little power so I would say about 40-60mA under max load once every 5 minutes. It takes very little in sleep mode like 5mA. I dont own one yet so I am just assuming this based of data I read on the internet

I think 2 panels is way overkill. With 8 hours of daylight and 50% efficiency that will result in 4Ah. That's 166mA you'll have available constantly. With that amount of power available you wouldn't even have to consider putting the arduino to sleep.

I don't have 8 hours of daylight. The direct daylight ranges between 1h in the winter to 6 hours in the summer and I also want it to be substainable in the winter. Also the lithium charger accepts input voltage from 4.5V to 5.5V .

I won't be able to tell you which solar panel or battery to use, but I can tell you how to figure that out.
Battery
For the battery there are a few different ways to figure this out:

The most common way to do this at the professional level is to build the device and run it attached to an energy meter and measure it for an hour or two performing its usage, and use that to calculate how much it will use over a 48 hour period. That being said that type of test equipment is not really a hobbyist piece of equipment and probably not something you are wanting to obtain for this project.
You can try and use the datasheets for all of your components to determine their idle and active current draw is, add them up for idle and active, adjust the values based upon the efficiency of your step up converter (so if it only 75% efficient, divide them by .75), guesstimate how long your sensor read process will take, multiply your active current draw times the voltage and times the time it will take (in hours, so if this is a few seconds, it will be a really small decimal), multiply your idle current draw times the voltage and times .083 hours (5 minutes), add those two together multiply it times 12 (12 - 5 minute periods per hour) and then by 48 (two days) and that will be an estimate of your energy usage for two days. Now this will be a very rough estimate as the datasheets only provide nominal values, and their actual usage in practice may be different, which leads me to the final option...
A hybrid between the two above solutions. Set up your device and have it read the sensors and transmit continuously. Then use a multi-meter to measure the current usage of it actively being used. Repeat the measurement again but this time with it running on an indefinite timer to simulate being idle. Then take those two numbers and use the above formula substituting the datasheet estimates with your actual measurements to get a much more accurate picture of what your energy usage will be.

Once you have your energy usage (this will be in milli-Watt-Hours or mWH) pick a battery voltage you will be using (this is based on the charge circuit you are using, typically, single cell lithium ion batteries are 3.7 or 4.2, with multi-cell batteries being multiples of those), divide your energy by the voltage to get the power (in milli-Amp-Hours or mAH) and you'll want to pick a battery greater than that. You'll also want to double check the data sheet of your step up converter and see what the drop out voltage is, and then compare that to the datasheet for the battery and see at what capacity it hits that voltage. You'll want to make sure that it is at least 80%. Otherwise you'll have to pick a different battery with a larger capacity, or a different step up converter with a lower dropout voltage.
Solar Panel
For the solar panel, what you will want to do is get a battery charger designed specifically for use with solar panels. This is because when it says 5.5v solar panel, that is it's nominal voltage in full sunlight, however, it most often will not be that and will vary greatly throughout the day. What this means is that solar panels are basically on unregulated power supply, and most battery chargers require a regulated power source. With a solar specific batter charger, it is designed such that it can handle voltage variation and sudden dropouts. Usually these chargers come with a recommendation as far as voltage and current requirements and those specifications should form the basis of your solar panel selection.
So for example, if you have a battery, on the datasheet it will list what its charge current is, and you'll want to make sure you have a charger circuit that can supply that amount of current. Then you'll want to take a look at the datasheet for the charger circuit, see what current it requires and then make sure that the solar panel can provide that current.

Wow thank you very much for this detailed answer. So I guess I'll have to calculate all the power draw of each component and figure out the battery size depending on it. About the solar panel: I found a lithium-Ion chargin circuit for it which requires an input of 4.5V to 5.5V, which is perfect for the solar panel I guess. How can I then figure out the solar panel power I need? Basically I have 1-5h of direct sunlight per day.

You will be unhappy if you attempt to connect the solar panel directly to the charger. You need a MPPT regulator, which will allow you to maximize the power drawn from the panel.

I've made an edit, see the bottom. I hope you are catching the general theme here: check the datasheet. Electronics work, especially power design, is more math than it is design. You just need to make sure that at each stage of power that you are providing enough current for the next device and that you are leaving enough extra room for power loss. Things like going from one voltage to another or charging a battery are not 100% efficient, so you have to add in some extra for tolerances.

Also to reinforce what I mentioned at the beginning of the Solar Panel section, and echo what Ignacio commented, you really should use a charging circuit designed specifically to work with solar panels. Here is one as an example https://www.sparkfun.com/products/12885 (this does not constitute an endorsement of this product). They can be a little more expensive than regular chargers, but not too much and totally worth it.


text:
Use Arduino to detect low battery state and shut it down
I wanted to know if it is possible to monitor a battery that is driving the Arduino and check its voltage. When the voltage drops below a certain level (i.E below 3.0V) it should shutdown and disconnect itself from the battery by using a relay or something. When the battery is full enough again it should power up again. Is that possible without any external sensors just by using the Arduino's inputs?

After it has "disconnected itself from the battery", how would it know that the battery is full enough again?

I don't really know, that's why I'm asking here. Maybe use a programmable attiny45 which controls the voltage and the relay? If that is not possible just shutting down is enough for me

It is not entirely beyond possible, in fact quite possible in theory.
I think the saying 'in theory, theory and reality are the same, but in reality they are not' is appropriate here.
So to monitor voltage, a simple voltage divider circuit can be used, and the Arduino can monitor that, and release a relay controlling the power line. The same relay could be wired to also reconnect when voltage reaches a threshold. I think the circuit actually requires 2 (or more) relays, and technically is it a kind of sensor, but since you indicated a relay was ok, it could work. So given those requirements, do you really need someone to draw it out, or were you just curious?

Simple battery monitoring from http://arduinotronics.blogspot.com/2012/04/voltage-monitor.html

I think I understood how the voltage detection works on the arduino. Yeah I would kinda need someone to show me how to do it as I'm really not advanced in this territory.

https://www.google.com/search?q=latching+relay&tbm=isch

That looks quite complicated, but I'll try to figure it out :)

I think that was my point, good luck :)

Have a look here
http://wp.josh.com/2014/11/06/battery-fuel-guage-with-zero-parts-and-zero-pins-on-avr/
It is for bare metal Atmel chip, but applicable to Arduino as well probably.
Step one in getting longer battery life is to move to a bare metal Atmel chip, choose ATMEGA or ATTINY depending on how many pins you need.
Also see my answer here
What are (or how do I use) the power saving options of the Arduino to extend battery life?

You also probably do not need a relay to disconnect the chip. Assuming you have the chip connected directly to the power supply with no regulator (which you do if you are running off battery), then you can just have your software put the chip into sleep mode which uses a negligible amount of power (micro amps). You can even set things up so that the chip will wake itself when the battery is reconnected to a charger. He is an example circuit and software using an ATTINY that does just that... https://github.com/bigjosh/Vibe-V2

I'm assuming Arduino is powered directly by the battery, and not via a voltage regulator. In that case you van measure VCC by first measuring the internal 1.1v voltage reference (in relation to Vcc). Since the internal 1.1v is constant and VCC will lower over time, the reading (0-1023) will increase.
See this article:
http://jeelabs.org/2012/05/04/measuring-vcc-via-the-bandgap/


text:
Industry Standard for Single-Board Computers?
Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor? I'm trying to sell management on using Arduino, but they are stuck on the question "what if Arduino goes out of business", and if I could answer "we can just switch over to using brand X because it's the same size and has the same connectors", my life would be much easier.

Arduinos are not single board computers.

@IgnacioVazquez-Abrams - untrue, an Arduino is very much an SBC

I'm going to agree with @IgnacioVazquez-Abrams -- the Arduino is just a microcontroller with a few extra peripherals attached around it to make it easier to develop with. Single board computer is generally a term for a board that has a Microprocessor (i.e. not microcontroller), some RAM, and optionally storage and maybe a GPU built in to the CPU. SBC would more like a Raspberry Pi or BeagleBone Black.

There are standards if you're willing to look beyond Arduino, such as PC/104, but for Arduino (hardware) you're pretty much stuck with whoever is making boards for them. You may want to consider standardizing your own I/O and Arduino libraries, and seeing how they work with the various Arduino-compatible MCUs.

@JakeC - no.  An Arduino has all of the same types of resources as most other SBCs - granted it is less powerful, but not less powerful than some of the first systems to define that term.  That a microcontrontroller puts peripherals such as volatile and non-volatile storage that might have once had to be a on the board on the chip itself doesn't mean that those functions aren't still present on the resulting board.

I guess that the Industruino is the closest you can get to an Arduino in an Industry Standard format; https://industruino.com/. The Arduino core and libraries is the real "standard". This is where the true value is.

Whether or not the Arduino company goes out of business isn't all that relevant. For one thing, there are now two competing companies vying for the Arduino trademark - arduino.cc and arduino.org.
The Arduino has such a ground-swell of popularity that clone boards are widely available on eBay and from other suppliers. While people are willing to buy them, someone will sell them.
The design is open-source, which makes it a safer choice than other designs who keep their design proprietary. For one thing, it guarantees that someone will make compatible boards, even if Arduino(s) fold.
The "heart" of the Arduino is (in most cases anyway) a chip from Atmel - so you really should ask if Atmel will go out of business. Probably not, but in any case, an alternative supplier might just as easily go out of business.
I wouldn't be building an "Arduino board" into a production system anyway - too much chance that wires would fall out of the prototyping sockets. However the prototyping board is good for learning about their capabilities, and testing your code.

Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor?

I'm not aware of any industry-standard form factor. The Uno design has caused a lot of people to make "shields" that fit onto that form factor, so that is probably the closest you would get to an industry standard.

If you need a real computer, there are nowadays various options based on the Intel NUC concept.
The Gigabyte variant, for example. It also has GPIOS accessible through a normal pinheader, in case you need them.
And, being x86, there is virtualyl no risk of loosing the supplier.

Modern x86 processors are not always perfectly deterministic even if you write to the bare metal, which is a trait desired in many embedded systems.

And where does that requirement come from, exactly?
For sure, not from the question asked.
Btw, the x86 processor is deterministic.
If you think you can write to the bare metal of an x86 machine you are fooling yourself, there is anyway a layer of microcode.
The amount of other SW running on top of it it might not be accurate, but that's a separate story. And, anyway, it was not a requirement.

No one was claiming that it was a requirement for this specific asker, nonetheless it is still worth considering before choosing a solution.


text:
iterate through values in an array of strings to print
I (think I) am trying to iterate through the values of an array and print the string to a tft. I have declared the array of 4 strings, and that works fine. But when I try to print it, I get garbage. Am I missing a nuance of print? Or do I just not understand how to use arrays and strings...?
The code is as follows:
Declarations:
//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

Use (note the fake if statement for the question)
  if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
    tft.print(displayActiveSystem);
  }

Instead I get random characters most of the time, sometimes nothing.
In case its a memory thing, please know that:
Sketch uses 26,480 bytes (92%) of program storage space. Maximum is 28,672 bytes. Global variables use 1,126 bytes (43%) of dynamic memory, leaving 1,434 bytes for local variables. Maximum is 2,560 bytes.

Maybe the baudrate is wrong? Or activeSystem is bigger than 3 and it gets out of bounds?

^ Bingo. I didnt have a catch on activeSystem.

I didnt realize how fast it looped and it went over in milliseconds. it then progressed through a bunch of memory spitting garbage all the way. Man I feel stupid right now

If the variable activeSystem exceeds the length of the array, it's out of bounds, at which point the behavior is undefined.
In your case you get "garbage data", which is actually just data in memory after the array.
Because the is no implicit check for array bounds, you need to check them yourself.

I think this is the correct way to create an array of C strings:
    char * hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    char * displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }

Since strings are basically stored as char pointers so an array of strings is an array of char * variables. Or you could create an array of Arduino strings:
    String hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    String displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }

I am not sure I understand 100% but here is my best shot. If the below is wrong
the issue is not due to being out of memory.
Try this
//Active System
char hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
// or char hvacSystems[4] = {"Off", "Fan", "Cool", "Heat"}
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
    tft.print(displayActiveSystem);
}

Your line
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
You are attempting to create a two dimensional array here. Essentially a 4x5 table. With your code if you do
tft.print(hvacSystems[0][1]);
It should give you "Off".  Basically you made a table that looks like
0{"Off", "Fan", "Cool", "Heat", null}
1{null, null, null, null, null}
2{null, null, null, null, null}
3{null, null, null, null, null }
Arrays:
https://www.arduino.cc/en/Reference/Array
2d Arrays:
http://forum.arduino.cc/index.php?topic=220385.0

It wont compile without the second dimension or with no dimension. Which makes sense if you consider that a string is an array of char's
[4][5]
0{"O","F","C","H"}
1{"f","a","o","e"}
2{"f","n","o","a"}
3{"/0","/0","l","t"}
4{null, null, "/0","/0"}

The problem does not appear to be what you think it is, because I can't reproduce it.
See this:
//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;

String displayActiveSystem;

bool systemNeedsToBeCycled = true;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  displayActiveSystem = hvacSystems[activeSystem]; // <-- Should now be String "off"

  Serial.println (displayActiveSystem);

  if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; // <-- Should now be String "Fan"
    Serial.println (displayActiveSystem);
    }
  }  // end of setup

void loop ()
  {

  }  // end of loop

Output:
Off
Fan

Please post a complete sketch that reproduces the problem. The placement of variables, and their type, might influence the result.
I used Serial.println() to show the variable contents, which are what you expected.

Possibly this will work better:
tft.print(displayActiveSystem.c_str ());

while you were hindered by my lack of code, the problem was there. activeSystem was unlimited and indexing invalid areas of hvacSystems after 3 loops. The loops run so fast that I missed the valid data at the beginning.


text:
Arduino bluetooth module as a server
I was looking around becouse I need to simulate a OBDII device. I think about to use Arduino for that. I was reading some tutorials how to use bluetooth module but I didn't find any tutorial when Arduino is a server. Alway Android app is a server. Is there way to put SP server in Arduino and Android as a client? And do I need special shield/module for that? If you could gave me some links to tutorials or code would be grate.
Interesting for me would be also possibility to send data form computer by USB to Arduino then Arduino push it forward to Android. - but that is not must have, first possibility is more importand for me.

You should say which bluetooth module you have. Some are client only others are client/server. All the server modules need to be configured as a server normally using AT commands.

I dont't buy yet, I wanted to ask first

There are two types of bluetooth devices for Arduino. Some are "slave" only and some are both "master or slave".
There is little difference in price so you should buy one that is master or slave.
This page (HC-05) describes one that appears to be commonly used but there are many and I do not have a recommendation. Some devices are in the form of small boards which connect to the pins on the Arduino (normally serial tx/rx) and some are shields that plug onto an Arduino. The article also shows the connection.
This appears to be an ODBII bluetooth arduino forum thread that uses bluetooth and ODBII. Video
By default Android is in bluetooth master mode. This article appears to show the Android programming required to enable a bluetooth slave.


text:
Controlling DC motor speed?
I'm trying to control a DC motor through L293D motor controller

const int controlPin2 = 4; // connected to pin 2 on the H-bridge
    const int enablePin = 3;   // connected to pin 1 on the H-bridge

void setup(){

  pinMode(controlPin2, OUTPUT);
  pinMode(enablePin, OUTPUT);

  digitalWrite(enablePin, LOW);
  digitalWrite(controlPin2, LOW);

Serial.begin(9600);
Serial.println("Ready");
}

void loop(){
if (Serial.available() > 0) {
    int inByte = Serial.read();

    switch (inByte) {
    case '0':
  digitalWrite(enablePin, LOW);
   digitalWrite(controlPin2, LOW);
 Serial.println("OFF");
      break;
    case '1':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 50);
    Serial.println("CW slow");
      break;
          case '2':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 100);
    Serial.println("CW slow +");
      break;
          case '3':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 150);
    Serial.println("CW medium");
      break;
          case '4':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 200);
    Serial.println("CW fast");
      break;
          case '5':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 250);
    Serial.println("CW fast +");
      break;
    case '6':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 50);
    Serial.println("CCW slow");
      break;
      case '7':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 100);
        Serial.println("CCW slow +");
      break;
      case '8':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 150);
        Serial.println("CCW medium");
      break;
       case '9':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 250);
        Serial.println("CCW fast");
      break;
}
}
}

It is working well except 1 to 5 are reversed:

1 should be the minimum speed
5 should be the maximum.

But it is back to front:

5 is the minimum speed
1 is the maximum speed

Any ideas?

Other than changing your case expressions?

So first thing, you should try to be more disciplined with your code formatting and the question...
FYI: it's best to use #define as it doesn't use memory for storing pin numbers... It's like Find and Replace in a text editor, this:
const int controlPin2 = 4; // connected to pin 2 on the H-bridge
const int enablePin = 3;   // connected to pin 1 on the H-bridge

Becomes this:
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

So this is the tidied up code, you can see the problem is a lot more approachable when the code is indented consistently, and good use of spaces and new lines is used...
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

void setup () {
    pinMode( controlPin2, OUTPUT );
    pinMode( enablePin, OUTPUT );

    digitalWrite( enablePin, LOW );
    digitalWrite( controlPin2, LOW );

    Serial.begin( 9600 );
    Serial.println( "Ready" );
}

void loop() {
    if ( Serial.available() > 0) {
        int inByte = Serial.read();

        switch ( inByte ) {

            case '0':
                digitalWrite( enablePin, LOW );
                digitalWrite( controlPin2, LOW );
                Serial.println( "OFF" );
            break;

            case '1':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 50 );
                Serial.println( "CW slow" );
            break;

            case '2':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 100 );
                Serial.println( "CW slow +" );
            break;

            case '3':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 150 );
                Serial.println( "CW medium" );
            break;

            case '4':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 200 );
                Serial.println( "CW fast" );
            break;

            case '5':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 250 );
                Serial.println( "CW fast +" );
            break;

            case '6':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 50 );
                Serial.println( "CCW slow" );
            break;

            case '7':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 100 );
                Serial.println( "CCW slow +" );
            break;

            case '8':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 150 );
                Serial.println( "CCW medium" );
            break;

            case '9':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 250 );
                Serial.println( "CCW fast" );
            break;

        }
    }
}

So your actual problem is that you need to reverse cases 1, 2, 3, 4, 5 to be 5, 4, 3, 2, 1...
There are two solutions:

Inelegant: would be to simply change the case numbers, they don't have to be in-order.
Elegant: copy and paste the code in each of the 5 cases about.

The result of option 2 is as follows, please feel free to confirm this is working?
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

void setup () {
    pinMode( controlPin2, OUTPUT );
    pinMode( enablePin, OUTPUT );

    digitalWrite( enablePin, LOW );
    digitalWrite( controlPin2, LOW );

    Serial.begin( 9600 );
    Serial.println( "Ready" );
}

void loop() {
    if ( Serial.available() > 0) {
        int inByte = Serial.read();

        switch ( inByte ) {

            case '0':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 250 );
                Serial.println( "CW fast +" );
            break;

            case '1':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 200 );
                Serial.println( "CW fast" );
            break;

            case '2':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 150 );
                Serial.println( "CW medium" );
            break;

            case '3':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 100 );
                Serial.println( "CW slow +" );
            break;

            case '4':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 50 );
                Serial.println( "CW slow" );
            break;

            case '5':
                digitalWrite( enablePin, LOW );
                digitalWrite( controlPin2, LOW );
                Serial.println( "OFF" );
            break;

            case '6':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 50 );
                Serial.println( "CCW slow" );
            break;

            case '7':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 100 );
                Serial.println( "CCW slow +" );
            break;

            case '8':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 150 );
                Serial.println( "CCW medium" );
            break;

            case '9':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 250 );
                Serial.println( "CCW fast" );
            break;

        }
    }
}


text:
xbee communication not established between arduino
I have 2 Xbee Series2 modules, one set to Coordinator AT (Connected to PC with XCTU via USB dongle) and other set to Router AT(Connected to Arduino is connected to PC USB... RX>TX  TX>RX and 5V GND)
http://continentalee.com.sg/xbee-adapter
My xbee adapter
I have the programme uploaded into Arduino, a very simple sketch to test xbee wireless communication.
Code is here
char msg = ' '; //contains the message from arduino sender
const int led = 13; //led at pin 13

void setup() {
Serial.begin(9600);//Remember that the baud must be the same on both arduinos
pinMode(led,OUTPUT);
}
void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}

The problem comes.
When I type "H" in the Serial Com, the led light up, and the letter "H" appears in the XCTU console.
however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino
Thank you for your help in advance.

Your example does not show your code that sends correctly but I will assume that it used 9600 speed and that the xbees are configured to 9600.
Not sure if this will help ...

Arduino is connected to PC USB... RX>TX TX>RX

1) In this case maybe you should ensure that xbee tx is connected to the correct rx pin on the Arduino? I know you have stated this above but with the basic xbee configuration, if data works one way then it should also work the opposite way.

however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

2) Your example doesn't show any code to send data to XCTU and the pin13 LED will only light up when an 'H' is sent from XCTU
You could try this for better diagnostics
    void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

      Serial.print("data arrived from xctu: ");
      Serial.print(msg);
      Serial.println();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}

Hi, thank you for your response. I checked the baud and the connection, everything is fine. Do you mind to enlighten me how to write code to send messages to XCTU using the arduino serial monitor

Hi, my code example shows how to do this. You should see a message in xctu showing the text "data arrived from xctu:". Have you configured xctu to 9600 baud and opened the port?


text:
How to use the native USB of the Arduino Due for high-speed communication?
All the Arduino examples involving communication via USB I could find use a virtual COM Port.
On the Arduino part it's
Serial.begin(baudrate);
Serial.write(byte);

And on the PC part it's just using a virtual COM Port.
However, the Arduino Due includes a native USB port, without all that UART+FTDI chip. I couldn't find any examples using the native interface, it seems everyone is content with communicating using the simple but slow way of Serial.write();.
How can I make full use of the native USB port, besides directly accessing the registers of the Cortex-M3, which seems to be a very tedious and complicated process? The data I would like to transmit is both large and time-critical, so I need to take care of buffer sizes, transfer types, etc., so writing characters one at a time to a general-purpose serial interface is not enough. The PC endpoint (I'm considering using libusb) should also see a proper USB device instead of a virtual COM port.

Sounds like it's time to move up to Atmel Studio.

Sounds like you need to use a HID interface.  I believe the Arduino core includes generic HID code, though I haven't used it, and I'm not sure it's actually enabled by default.

@IgnacioVazquez-Abrams Atmel studio Requires an ISCP, right?


text:
no response in recieving with arduino uno by nfr905
from examples of  RadioHead library .
https://github.com/PaulStoffregen/RadioHead/tree/master/examples/nrf905

I tried the client and server examples ; the client was fine with no errorrs and the serial monitor showed the demanded data but I had a problem with the recieving side , the Rx led did not light on and nothing in the serial monitor had been showed .
what's the matter !?
and I did'nt change anything in both codes .


text:
How to read pH value
I am trying to read the pH value from a analog pH meter, SEN-01454. From the source code I found, voltage maps to pH value. This is the code:
pHArray[pHArrayIndex++]=analogRead(SensorPin);
      if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
      voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
      pHValue = 3.5*voltage+Offset;
      samplingTime=millis();

But then the value is not correct. So how do i actually do it.
The example code from Wiki page for product.

What value do you expect?

the value of the liquid

ok a bit more specific, what liquid are you testing. Do you know what that liquids' pH is, this is of use if you are calibrating it. If you are testing a liquid and don't know its pH before testing you might actually be getting the right value.

Sodium Hydroxide which is pH value of 12.

and the value you are getting?

This is SOME of the code. We are missing the avergearray() function.. I suspect you're taking one reading and averaging it with both old & future ones, but this code clearly is meant to sit in a loop..
From another source, I got this:
/*
# This sample codes is for testing the pH meter V1.0.
 # Editor : YouYou
 # Date   : 2013.10.12
 # Ver    : 0.1
 # Product: pH meter
 # SKU    : SEN0161
*/

#define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
unsigned long int avgValue;  //Store the average value of the sensor feedback
float b;
int buf[10],temp;

void setup()
{
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial.println("Ready");    //Test the serial monitor
}
void loop()
{
  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=analogRead(SensorPin);
    delay(10);
  }
  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }
  avgValue=0;
  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    avgValue+=buf[i];
  float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
  phValue=3.5*phValue;                      //convert the millivolt into pH value
  Serial.print("    pH:");
  Serial.print(phValue,2);
  Serial.println(" ");
  digitalWrite(13, HIGH);
  delay(800);
  digitalWrite(13, LOW);

}

which reads in the array first and then averages it. Is this what your code does? If so, what sort of errors are you seeing?

There is no error. But i can't get the correct value of the pH

So what values do you get instead? And, with respect, there probably is an error - or it would work!


text:
Change arduino.local server address
I have a Yun and I'm trying to change the URL I type in to access the Web UI.
I've successfully changed its hostname in /etc/config/system, which now lets me SSH in using the new name. However:

Going to newname.local doesn't work (no response at all).
Going to arduino.local pulls up the green page 'Wait a moment or click here...', after which no page is rendered.

How can I access my Yun by typing in newname.local in my browser?

That should be working fine.
I just logged into my Yún and changed its name by editing that file.  I then restarted avahi-daemon since that is what broadcasts its name (faster to restart the daemon that reboot the whole Yún).
Browsing to the new name worked fine.
matt@dell:~$ ssh root@arduino.local
root@Arduino:~# vi /etc/config/system
(edit the config file)
root@Arduino:~# hostname skybridge
(manually changing the hostname so I don't have to reboot)
root@skybridge:~# /etc/init.d/avahi-daemon restart
(restart the avahi daemon)

Browsing to skybridge.local now shows me the Arduino login as it should.
As a further test I have just rebooted my Yún so it runs everything from scratch and it still works fine.
There are a number of caches involved in the system, any of which may be getting in the way.  It could be that the browser has cached incorrect or out of date information about the FQDN (fully qualified domain name) for the name you have given your Yún, in which case just closing and re-opening your browser may help.  It may be that the mDNS lookup system on your computer (you haven't mentioned which operating system you are using, which is a big factor) has cached old or out-dated information for the FQDN, in which case flushing that cache may help (how you do that depends on your OS), or just rebooting your computer.
Incidentally, if you are on Linux (Windows lacks these basic networking facilities along with many other basic tools), you can query the network for your Arduino Yún with the avahi-browse and avahi-resolve commands.  OS X has similar tools, but I don't know off hand what the commands are:
matt@dell:~$ avahi-browse _arduino._tcp
+  wlan0 IPv4 skybridge                                     _arduino._tcp        local
^CGot SIGINT, quitting.
matt@dell:~$ avahi-resolve -n skybridge.local
skybridge.local 192.168.0.252

Thank you very much for your answer - I'm going to test it and get back to you.

It turned out that the method did work. For some reason it didn't respond consistently right away, but a day or so later. Thank you!

@sscirrus Probably a cache that needed to expire then.  They can be pesky sometimes...


text:
How do I upload sketch (and parameters) through a user interface
I'm pretty new to Arduino and I'm developing my first real-world project.
I have a Arduino Mega with a full working sketch in it which is going to be placed in several distant places and I have a number of "mantainers" that will need to get to the place, connect the board with their Windows (Vista+) laptop (USB), upload a new version of the sketch (if available), download some data from EEPROM and change (if needed) some parameters stored in PROGMEM. This just to give you the full picture, now I come to the questions.
What I'm trying to attempt is to write (in c++) a software that gives non-programmers a UI to do this stuff easily, so I wonder:

How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?
When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

The data in PROGMEM is actually part of your program: it is embedded in the .hex file you upload to the board. If you want to change persistent data without re-uploading the whole program, use the EEPROM instead of PROGMEM.

@Edgar That's bad news, but thank you for pointing it out! This simplifies the process (update the sketch - talk to the sketch through serial - the sketch writes on EEPROM) but EEPROM is little enough as it is... Does it make sense to you to write my parameters in a text file and then compile the sketch on-the-fly (with this data in) through my UI using the CLI of Arduino IDE (which I would include in my software)? Choose one: A - it makes sense; B - no it does not; C - ask a new question for this

I would go for the EEPROM if at all possible. If not, write the parameters to a binary file and link the sketch with that file (c.f. my updated answer). No need to recompile. Not sure the CLI of the Arduino IDE can do that, but avr-ld can.

How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?

Yes, you have to use avrdude.  The simplest way is just to bundle avrdude.exe and the avrdude.conf file with your program and call it, along with its required parameters, with system() or some similar (eg execv()) method (or whatever Windows has decided to provide instead of those standard functions - who knows what goes through the minds of Windows developers...).

When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

When you upload a new sketch you are writing to PROGMEM.  That's really the only time you can do it.  Yes, there are ways you can write pages of data to PROGMEM, and that's exactly what the bootloader does when you upload a sketch, but manipulating individual variables in PROGMEM is not possible without major brain surgery being done in your sketch.  To store these kind of tweakable parameters you would normally use the EEPROM.
It can also be good to use external storage for some of these things to - either an SD card (overkill) or an external SPI or I2C EEPROM or Flash chip.  This keeps all the data completely separate from your sketch so you can never overwrite that data when you upload a new sketch.
It is, of course, up to your sketch to provide some kind of interface to tweak the settings, whether stored in internal EEPROM or an external EEPROM chip.  Creating some kind of serial protocol which your C++ program can interface with will be essential.  Only while your sketch is running will you be able to change those variables.  If you don't want to allow end users access to that interface then one method could be to have a separate sketch which is a "calibration and configuration" sketch which your program uploads in order to adjust the settings.  Once you have finished it then re-uploads the original (or new) sketch to allow normal operation again.

When I'm on air I'm quite comfortable, I already have a serial protocol to communicate with the sketch. It was the upload part I had no clue about! Answer accepted, thanks a lot!

Does it make sense to you to write my parameters in a text file and then compile the sketch on-the-fly (with this data in) through my UI using the CLI of Arduino IDE (which I would include in my softwareas well)? Choose one: A - it makes sense; B - no it does not; C - ask a new question for this

I choose D: it depends on what the data parameters are and how big they are and if it's worth the extra effort.  If you choose to do it that way you will need to include the compiler with your program which will make it much bigger and more complex to install.

1) Why not just
system("avrdude ...");

That's more or less what the Arduino IDE does.
2) If you really want to embed the data in the executable, see
Embedding Blobs in
Binaries.
You would need to re-link and re-upload the program each time you change
that data. You won't need the Arduino IDE, as it's only job is basically
to call avr-g++ and avrdude. You can use the IDE if you find it's CLI
easier than those of the standard tools.
If you put the data in EPPROM instead, the avrdude can upload it without
re-uploading the program.

So I would have to include the avrdude executable into my software installation?

Definitely. It's part of the Arduino installation BTW.

The avrdude/upload part has been fairly well covered by the other answers, but what has not been mentioned yet is that it is fairy trivial to modify program memory contents by modifying the hex file to be uploaded.
Basically, you just write hex-encoded bytes in the correct place in the file, and then update the checksum at the end of each line you modify.  It can help if you put a readily recognizable placeholder sequence in the desired location in your source code, which you can look for in the hex file as an extra verification you are making your substitutions in the correct place.  This is fairly straightforward string processing and unsigned byte math which you can accomplish in the language of your choice.  There are also tools which can convert between hex files and binary images, and probably tools or libraries which can fix the checksums for you.
Do pay attention to the license terms of avrdude and any other non-original code or tools you distribute.

I'll keep this possibility very much into consideration, thanks


text:
Reading Arduino from Java is way too slow
I am trying to write a simple Java program to display the analog input fed to an Arduino board upon a stimulus from a user on some physical sensors.
If I use the Arduino program itself and look at the serial monitor, I see the analog read based on user input updated instantly. However, when reading the input from my Java program, there is a significant delay (8-12 seconds) between the physical stimulus and the display of the value.
The code uploaded to Arduino is very simple, just cycle through a bunch of analog ports and print the data:
void setup() {
  Serial.begin(9600);
  pinMode(30, OUTPUT);
}

void loop()
  digitalWrite(30, HIGH);

  for (int i = 0; i < 10; i++) {
    int sensorValue = analogRead(i);
    Serial.print(String(i) + ":");
    Serial.println(sensorValue);
  }
}

The Java code I am using is almost entirely copied from the example provided here, with the exception that I updated the port name to work for my system (Mac OS X 10.10.3).
Here is the Java code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class SerialTest implements SerialPortEventListener {

    SerialPort serialPort;

    /** The port we're normally going to use. */
    private static final String PORT_NAMES[] = {
            "/dev/cu.usbmodem1411",
            "/dev/cu.usbmodem1451",
    };

    /**
    * A BufferedReader which will be fed by a InputStreamReader
    * converting the bytes into characters
    * making the displayed results codepage independent
    */
    private BufferedReader input;

    /** The output stream to the port */
    private OutputStream output;

    /** Milliseconds to block while waiting for port open */
    private static final int TIME_OUT = 2000;

    /** Default bits per second for COM port. */
    private static final int DATA_RATE = 9600;

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        //First, Find an instance of serial port as set in PORT_NAMES.
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            // open the streams
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            output = serialPort.getOutputStream();

            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }

    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws Exception {
        SerialTest main = new SerialTest();
        main.initialize();
        Thread t=new Thread() {
            public void run() {
                //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
    }
}

All the program does is print out the values of the Arduino serial monitor, yet it takes way longer (8-12 seconds) through Java than it does from the Arduino program itself.
1) Why is this happening?
2) How do I fix it?

Are you sending full lines each time, including a full line terminator?

I am just a beginner, I think you mean a string terminator to denote a new line, but I am not sure what you are referring to. You can see all of the code. And it does work both in Arduino IDE and in Java just that Java takes much much longer, so I would think that is not the issue? Please elaborate

After the 8-12 seconds, does it keep displaying at a fast enough speed?

This seems like a host OS / serial API / Java problem not an Arduino one.  Try putting the readLine method in a blocking loop in your main thread to simplify things.   Historically, there have been some very pathalogical interactions between application layers, operating systems, USB-serial firmwares, and the corresponding drivers - I've seen something that worked just fine with a C program effectively read at around 100 baud with a .NET client running on the same machine.

Try adding a delay (eg. delay(200);) into your main loop. You may be sending data too fast for the Java app to cope with.

Yes that was the issue!! I put some delays in there and the performance is way better. It is still not perfect, but I bet if I keep playing around with the delay I will get it. So far much improved though good thinking!

I'm glad that helped. I'm going to flag your "answer" as "not an answer" (if I don't someone else will) because the answers are supposed to be an answer to the question. Unfortunately I didn't post what turned out to be the answer, as an answer myself. Oops. Thanks for letting us know that it worked.

I turned my comment into an answer, mainly to help the next person who looks at this question. If you can mark it as "accepted" that will also help them. Thanks!

Timing tests show that the Java code lags something like 25 or more seconds behind the input from the Arduino. This can be fixed by changing in the Java code these lines:
       try {
            String inputLine=input.readLine();
            System.out.println(inputLine);
        } catch (Exception e) {

to:
       try {
            while (input.ready ())
              {
              String inputLine=input.readLine();
              System.out.println(inputLine);
              }
        } catch (Exception e) {

This extra loop "drains" the input buffer of data in the one serialEvent call, rather than relying upon a serialEvent call per line of data.
I found when testing that the output is now highly responsive, even without a delay on the Arduino side.

My other answer of adding a delay call slowed output down enough for the Java app to catch up, but I must admit it isn't the best solution.

One more thing you could do is create a while(true) loop, after initialize() and call input.readLine(), so that you don't wait for the event to appear.
For some reason the event is delayed, but doing the while loop hasn't created any issues or exceptions for me so far.
My code is like this:
public void initialize() {
   //initializing stuff
   while(true){
       try {
           String inputLine = input.readLine();
           //do stuff here
       } catch (Exception e) {
           System.err.println(e.toString());
       }
   }
}

Try adding a delay, eg.
delay(200);

into your main loop. You may be sending data too fast for the Java app to cope with.

No.  An arduino transmitting at a mere 9600 baud should not be able to outpace the program, unless there is something pathologically wrong with the program or the installation it is running on.  If this has any effect at all, it was probably only in changing some highly unfortunate "just missed it" to some slightly less problematic one, but that actual problem remains and may rear its head again in a different configuration.  This is not a sound solution or based on any sensible reasoning - if it helps at all, it is only by lucky accident.

Thank you for your comments, Chris. Rather than trying to salvage this answer (and have your comment make no sense) I have posted another answer.


text:
Blutooth shield LED control
I am trying to control a led ON/OFF using Arduino UNO and a Bluetooth shield
I have this

which is based on hc-05. The tutorials I found about hc-05 are not working for me. I have the hc-05 embedded in the shield and I did not  find any tutorials  for this shield.
Here is my code (it is working when I use the USB serial ctrl + shift + m).
void setup () {
pinMode( 13, OUTPUT );
digitalWrite(13,LOW);

Serial.begin( 9600 );
Serial.println( "Ready" );
}

void loop() {
if ( Serial.available() > 0) {
    int inByte = Serial.read();

    switch ( inByte ) {

        case '0':
            digitalWrite( 13, LOW );
        break;

        case '1':
            digitalWrite( 13, HIGH );
        break;

    }
 }
}

I connected my android phone to the shield successfully using blurterm2. When I send 1 or 0 nothing happens. What am I missing?

If I understand your board the LED is on output 4. You should try to control it with simple on/off "hello world" logic before adding the serial input. If you connect the green lead to Vin does tshe LED light? If not, it is reversed or dead.

i connected the led to pin 13, it is blinking when i control it from usb serail http://s10.postimg.org/izvhgzluh/20150710_173523.jpg

Have you tried the turning just running a simple program to check if the led still works, such as
void setup () {
pinMode( 13, OUTPUT );
}
void loop() {
 digitalWrite( 13, HIGH );
 delay(1000);
 digitalWrite(13,LOW);
 delay(1000);
}

Yes the code you gave me is blinking the led

From your code I cannot see anything that actually initializes the shield and tells it what pins to use and how to use them. This github (https://github.com/jdunmire/HC05) has a library for the HC-05 shield and it appears to have instructions for setting baud rate and all of that good stuff.
Also, their read-me mentions that, if properly configured, you should see traffic to and from the shield in your serial monitor. Are you seeing any traffic?
NOTE: This tutorial (http://www.instructables.com/id/Arduino-AND-Bluetooth-HC-05-Connecting-easily/?ALLSTEPS) seems to have step by step instructions to do exactly what you are asking.

You should use a different baud rate if your hc-05 does not work with the code. The default is 9600. Use this baud rate and if not, try to find out the baud rate using AT commands, you will get several tutorials on this.

Here is your problem:
if ( Serial.available() > 0) {
int inByte = Serial.read();

You are not listening to the bluetooth-hardware, but to the build-in serial port of the Arduino.
I had a look at the url you can see on the board, but i could not find any example code. If you are lucky your bluetooth should might be compatible with the freetronics bluetooth shield, which has some example code on the bottom of this page to get you started:
#include <SoftwareSerial.h>

SoftwareSerial bt(2,3); // RX, TX

int thisByte = 33;

void setup() {
  bt.begin(9600);
  bt.println("ASCII Table ~ Character Map");
}

void loop() {
  bt.write(thisByte);

  bt.print(", dec: ");
  bt.print(thisByte);
  bt.print(", hex: ");
  bt.print(thisByte, HEX);
  bt.print(", oct: ");
  bt.print(thisByte, OCT);
  bt.print(", bin: ");
  bt.println(thisByte, BIN);

  if(thisByte == 126) {
    thisByte = 32;
  }
  thisByte++;
}

This only sends, and "bt" is your bluetooth hardware here. It behaves like the Serial hardware for the most part.
Note: based on your picture, you might have to change the RX/TX pins on your board to 2,3 - currently they are set to 2,4.


text:
xBox receiver code output is scrambled
I'm running the following code:
#include <XBOXRECV.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
XBOXRECV Xbox(&Usb);

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nXbox Wireless Receiver Library Started"));

}

void loop() {
  Usb.Task();
  if (Xbox.XboxReceiverConnected) {
    if (Xbox.getAnalogHat(LeftHatY) == 0) {
      Serial.print(Xbox.getAnalogHat(LeftHatY));
    }
   Serial.print("TEST");
  }
}

After running the example that the library includes and a spin off I wrote for test purposes I keep getting random output, this is just some of it:

9�]==�=�~=���y��:.�:�:����9�=��������:�:�\=���^=�?�}�:^���:�|]=9�\=��������:�ܗ��.\�~=���

Have you changed the baudrate in the serial monitor to 115200?

Seems like wrong baud-rate. Change baud-rate in the Arduino IDE serial monitor.


text:
Is it possible to setup a CAN-BUS Arduino Shield to communicate with SocketCAN for UNIX?
I have an Arduino + SparkFun CAN shield, and I was hoping to set it up to work with candump on an Ubuntu system. Is this doable, or is candump made specifically for raspberry Pi's?

What's candump? How about providing some links, eg. to the shield and whatever candump is.

what do you mean "set it up to work with candump"? What are you trying to achieve? Are you trying to use an Arduino to expose a CAN bus to the linux candump?

Yes. Normally you would write a linux kernel driver to communicate with your device (arduino) following your own protocol, but SocketCAN provides by default a way to interface with Lawicel dongles, whose communication protocol is publicly available: CANUSB / CAN232 protocol.
Many people have built arduino sketches that implement this protocol so you can use your arduino with SocketCAN in Linux (candump, cansniff...) as if it were a Lawicel dongle.
You may find this useful:
https://github.com/autowp/arduino-canhacker
https://github.com/kahiroka/slcanuino