text:
Arduino filling serial buffer with nulls
I just wrote some code that just sends a string from Arduino to Processing.
Processing prints the string and displays the number of characters in the buffer...
After uploading the sketch to the Arduino and starting Processing for the first time, the serial buffer is initially filled with a few things (it turns out that these are nulls; 0 in ASCII). Why is this happening?
And this mostly happens after uploading and starting Processing for the first time. When I start Processing for the second time, the buffer is initially free as it should be. I am using a genuine Arduino Uno. I also tested on another Arduino and another laptop, but there is still the same problem. So it should not be a hardware problem.
Arduino Code
void setup() {
  Serial.begin(9600);
  //delay(1000)
  Serial.println("the quick brown fox jumps over the lazy dog");
  delay(1000);
}

void loop() {
}

Processing Code
import processing.serial.*;
Serial myPort;

void setup() {
  myPort = new Serial(this, "COM3", 9600);
}

void draw() {
  if (myPort.available()>0) {
    println("Buffer:"+myPort.available());
    String string = myPort.readStringUntil('\n');
    if (string!=null) {
      println("String:"+string);
    }
  }
}

In the image is other code just to show that the buffer contains nulls.

Is is an Arduino or an ESP? (Because the latter prints some data on boot, using a different baud rate, IIRC: 76800. This MAY result in nulls if you try to read them using a different baud rate than they're sent in, but usually results in garbage.)

I am using an Arduino Uno.

Not able to replicate your problem here with 1.8.19, avr core 1.8.5, processing 4.0.1, windows 10 and official UNO. Are you using something like a CH340 based clone?

The Arduino that I got is genuine not a clone.

Have you tried this myPort.bufferUntil(lf); in setup()? https://processing.org/reference/libraries/serial/Serial_bufferUntil_.html

There are a lot of these kind of questions on Stack Overflow (though I haven't seen this particular problem). Sample. Many solutions include catching exceptions (in Processing). A list of 347.

Does the Arduino restart when connected to?

Timing issues have been reported.

Provide versions numbers of everything involved like I did in explaining my attempt to replicate your problem.

versions are the same as yours.
Arduino 1.8.19,  Processing 4.0.1

What happens if you connect a 10 kOhm resistor from D1 to 5V?

If the problem is a matter of timing of the startup of the two microcontrollers on the Arduino Uno (e.g., the serial RX input is floating for some fraction of a second (or even more)), starting setup() with a pause of, say, 5 seconds, could alleviate the problem.

(On some Arduinos, e.g. Arduino Leonardo, the external pull-up resistor would not work there as it is for the second serial (hardware) port.)

@PeterMortensen that idea is part of why I asked the question. However I've since confirmed that the firmware for the Xu2 chip on the official UNO does in fact enable its internal pullup.

I tried connecting D1 to 5V but nothing changed

@PeterMortensen the Problem is alleviated by adding a 5 seconds delay before Serial.println(), but this makes the program slow.

In my tests, the only way I've been able to get anything approaching your sample output on an official UNO R3 is by pulling D1 toward ground strongly enough to cancel out the effect of the XU2's internal pullup. Do you have nothing besides the USB cable attached to your board when you're testing this? What kind of environment are you running this in? Have you tried a different computer? Have you tried a different UNO? Do see the exact same NUL characters if you use RealTerm?

@timemage I have nothing else connected to the board. I am using Arduino IDE 1.8.19.
I already tried the same code on a another arduino with another Computer. But those nulls still there. The number of NULL characters differes every time I upload the sketch. It is not the same number everytime.

Well, keep adding details. I'm able to recreate your test scenario in as far as it has been described, where the current answer to "Why is this happening?" is "It isn't." or at least "It isn't here." If you new details or a picture or something, I'll look at those and see if I'm replicating your setup accurately.

Re "by adding a 5 seconds delay before Serial.println(), but this makes the program slow.": No, I meant at startup, in setup(): A delay, before any set up of the serial hardware, as the very first statement / call. The 5 seconds is a very conservative number. It can successively be cut in half until the minimum required (empirically found) time has been found. It may only be 30 ms. But start with a very long time.

@timemage: I don't understand it either. I have now measured on a genuine Arduino R3 (not a clone) with a very weak pull-down resistor (1 MΩ - measured to 1.02 MΩ). The RX line was not asserted high until about 5 ms after the RESET signal went high (I measured 5.3 ms from RESET signal reached 2.0 V till RX went high). But a very simple sketch where the very first action in setup() was to set D12 to output and then high took a whopping 1.5 seconds (I measured 1.56 seconds), about 300 times longer. The Arduino was powered through the USB cable (and connected to a Linux system).

I also verified the 1.5 seconds with a stopwatch, by setting D13 (LED) high immediately after D12. I measured about 1.8 seconds from power on till the LED lit up. With reaction time, about 0.3 seconds, 1.5 seconds is about right.

Is there a way for setup() to execute sooner?

Related: What happens on Arduino power-on, and how long does it all take?. 1.544 seconds was measured on an Arduino Uno R2. Start your Arduino instantly - no boot time without bootloader

OK, I got it the wrong way around. Robot12, what is the exact startup sequence of the two systems, the Processing program and the Arduino, (incl. approximate timing)? For instance, is the Processing program running while the Arduino is being programmed? What do you actually do? Can you add the steps/the procedure to the question?

If connecting to the COM port from Processing results in a RESET on the Arduino then the TX line could be floating for a number of milliseconds.

Only the first COM port connect/open after power on of the Arduino results in a RESET (at least on Linux, using 'Screen' as the serial monitor), pulse width about 600 µsec if a 2.0 V threshold is used (but it is a ill-defined RESET signal, RC charge up on the rising edge). Thus the system has a state on which the observed behaviour may depend on: 1) Connected to once. 2) Connected to more than once.

Further, TX does not change during such a "soft" RESET by connection, only during power up. The timing during power up for TX is similar to RX: TX is asserted high 5.2 ms after RESET becomes 2.0 V.

Correction: "... has a state ...  1) Never connected to. 2) Connected to one or more times.

(And the "soft" RESET by connection actually has an effect: the D12 control signal is unasserted (input) for 1.51 seconds, as expected.)

I'm not sure I'm going to be able to follow all of what you've said above now. But regarding the part you addressed me about "The RX line was not asserted high until about 5 ms after", the thing I was testing was the transceivers RX (AVR's TX) because that's what's in play here. And that may well float for 5ms during power-on of the transceiver. However transceiver is also not trying to receive anything during that time, so it hardly matters. I ignored the other direction for a number of reasons, most of it related to fact that the first example doesn't read anything at all on the AVR.

@Robot12: Did you make progress?

sorry for the delay responding. I just ignored these Nulls and kept working on my project.


text:
Increasing the numbers of I/O pins on Arduino Uno
I want to make a game of Tic-tac-toe using an Arduino, LEDs and bouncy buttons. Hence I need nine inputs and nine outputs. But you see that an Arduino only has 13 I/O pins. So is there a way I can use the analog pins or a way to reduce the number of I/O pins using an ingenious way?

possible duplicate of Is there a way to have more than 14 Output pins on arduino?

See Is there a way to have more than 14 Output pins on arduino? - there is a lengthy discussion there, with references.

I added an answer to the question Nick mentioned, with a note about accessing 7 I/O lines from the Atmega16U2 on the Uno.

Have a look at charlieplexing

This question is similar to Creating an Arduino Tic Tac Toe game.

Yes, just use the analog pins. The analog pins are both analog inputs and digital I/O pins. The functions happen to be shared on the pins, in the same way that the interrupt pins are shared with digital I/O, the TX and RX pins are shared with digital I/O and the SPI pins are shared with digital I/O.
Every I/O pin (analog or digital, etc.) can be used as digital I/O.
You can also reduce your required number of I/O pins by using a technique known as multiplexing.
For instance, to read nine buttons you could have them arranged (as in Tic-tac-toe) in three rows of three buttons. You then have three I/O pins for the columns and three I/O pins for the rows - that's just six I/O pins for nine buttons.
The technique is widely used for keypads, but they are just buttons, so the same technique can be applied to any buttons.

The Matrix Keypad how-to

The same can go for LEDs. There are various specialist LED multiplexing techniques that allow for many LEDs to be driven from just a handful of I/O pins.

How to Multiplex an LED Grid... (YouTube)
Charlieplex Library for Arduino

You can also multiplex buttons with LEDs, this way you just need 3 pins for commons + 3 pins for LEDs + 3 pins for inputs.

If multiplexing is too complicated for you, you can wire all buttons to one analog pin using resistors. This way you only need 9 pins for LEDs and 1 analog pin for buttons.

What I am planning to do is that use rgb leds, So if user 1 presses some button then red color and then next one green. So I guess that this method would not be able to work that way, because they require different voltages. And all this process have to be dynamic. I don't know which button will the user be pressing.

source: Stack Exchange

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

sort: votes


text:
Using Visual Studio Code to program an Arduino
I had recently got an Arduino Uno and did quite a few programs on it. Now, I had always used Visual Studio Code to do my C projects. So, is it possible to use Visual Studio Code to program an Arduino, but without the Arduino plugin available in Visual Studio Code?
This might sound a bit weird, but I wanted to learn how to build those type of plugins from scratch. Are there some resources from where I could learn to do that? I searched through Google, but I couldn't find any answers.

Install extension Arduino by Microsoft. its very simple to configure and use.  for larger projects i would recommend platformio, BTW did you try new Arduino IDE2? if not give it a try, its much better than before.

This might not be the answer you are looking for, but maybe it helps you and others. Besides, it's too long to write as a comment.

Use VS Code only as editor
Make sure that your .ino file is as small as possible, typically, just enough to call a second file (.cpp or .c file). The idea is that you do not need to change the .ino file often as you need to load the .ino file only in your Arduino IDE. All other files (including the .ino) you load in VS Code.
Than you edit your files in VS Code as asual, but you compile/upload the file with the default Arduino IDE. The Arduino IDE doesn't see files being saved as new, so that's why you need not to change the .ino file often, as you need to synchronize it manually.

MS Visual Studio
I'm using MS Visual Studio, comparable to VS Code and written stubs or even emulations for certain Arduino classes (like Arduino, but also for other libraries I use on the Arduino, which mimic or at least print something when called).
This way I can fully compile an Arduino project, and most important, run it so I can check the business logic and some parts of the hardware logic on a normal PC having a decent debugger etc. When working, I can use the first solution to upload it to an Arduino.
Writing these stubs is quite some work and the simulation can depend on the project (like for a LED strip project I actually visualized the LEDs on a PC).

In both above cases, I use the Arduino IDE only for compiling and uploading, not for editing. It would be also useful to skip using this Arduino IDE completely by using a command line to compile/upload using the CLI version of Arduino (see comment of theBusyBee below. In at least Microsoft Visual Studio but probably Visual Studio Code external commands can be added calling this Arduino IDE for compiling/uploading.

PMF's comment below: You can use VisualMicro on top of  Microsoft Visual Studio; this is a paid extension.

You might want to add that the Arduino infrastructure allows building by the command line. There are also some questions here...

@thebusybee That's indeed a good addition. Not sure which questions you refer to.

Well, my free time is heavily limited, so I don't think I can search for and choose one. Perhaps someone else can do this and add it to the answer.

It's just 3 options (or options on top of each other).

Oh, I think we have a misunderstanding, perhaps. I meant that some questions here on SE/Arduino refer to CLI usage and might have good answers, worth to link to them. I did not mean that some points in this question are left open.

Ok clear ... I assume that with option 3, people will realize they can also use the CLI directly without any of the IDE's mentioned and search for that themselves.

Because Visual Studio was mentioned: There's actually an extension called "VisualMicro" that adds all features of the Arduino IDE to Visual Studio (+ a live debugger). It's not free, but cheap enough also for private projects.

@PMF: Thanks, I added it to the answer (with your name of course)

If you really looking for an alternate for Arduino IDE. Than I will recommends you to go with platformio. It has great library management.
Just install the platformio extensions on the vs code and you are ready to go.

You can write C++ file with the editor of your choice, include avr/io.h to manage Arduino I/O, and then compile with avr-gcc and upload with avrdude. This is what I do because I don't like working with the .ino sketch directory structure that hides away normal C++ code that you would use with any other microcontroller. (See What is the relationship of an Arduino .ino file to main.cpp?, Why does an `.ino` file have to be in a folder of the same name?)
Guide: https://create.arduino.cc/projecthub/milanistef/introduction-to-bare-metal-programming-in-arduino-uno-f3e2b4

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


text:
Post Data To a Web Service From Arduino
If you want to submit sensor data such as temperature to a remote server/database somewhere you need to use some kind of call to a web server since it isn't possible to connect directly to a database from the Arduino.
How do you post data to a JSON web service from an Arduino that's connected to the Internet?

What web service are you using?

It will be one I write.

There is the aJson library that allows you to work with JSON objects in Arduino.
However, depending on the complexity of your program, I would just do it manually to save memory. You may be able to just copy the functions you want out of the library.
Then check out the WebClient library which has an example for making a POST request at the bottom.

Check this from Arduino docs.
In the "Post method request" code example just define your JSON as plain text like char jsonData[] = "{name: 'yourName', data: 'yourData'}" for example, and then call byte postPage(char* domainBuffer,int thisPort,char* page,char* thisData) function passing "jsonData" variable defined before for "thisData" parameter.
It worked for me, hope it helps.

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


text:
Infrared TV Remote to Arduino
On the hardware side of things, what is involved in making the Arduino receive signals from a TV Remote? What kind of infrared receiver is needed? Do TV remotes use some kind of channels, encoding, or encryption requiring special receivers or else additional programming work to decrypt the signals?

I would checkout http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html it explains locations to look to understand some of the protocols required to communicate with specific brands.

The most common (not sure what others are used) carrier frequency is 38khz. You need an IR receiver tuned to that frequency to get the signal from the remove. See this page for way more information.
There is no encryption or special receivers needed as long as the carrier frequencies match.
That's really all the hardware you need. On the software side of things, you read this signal and decode it. There's a neat little library for doing exactly that. It's called Arduino IRemote.
It even has an example sketch which tells you just what the decoded value is of whatever button you pressed so you can use that in your other programs.

Responding to TV remotes is surprisingly simple, because they typically all work on exactly the same principle, with no concept of channels or encryption.
What you need is an IR receiver module, which you can buy fairly cheaply from many electronics suppliers. Anything intended to work with remote controls should be suitable. The important part is that it will work with ~38 kHz signals.
It will typically be a 3 pin component. Many are able to operate at 5 volts, which means you can usually connect the IR module's voltage and ground pins directly to the Arduino's power supply. The data (or signal) pin can typically be connected straight to any GPIO pin. Always check the component's data sheet though. It will often recommend using some additional components (e.g. resistor and capacitor) to smooth out power fluctuations. That shouldn't be necessary for a small project though.
When an IR signal is detected, the module will usually output a series of pulses on the data pin. These will be digital pulses, so there's no need to use an analog-to-digital converter. What matters is typically either the length of each pulse (Pulse Width Modulation), or the length of the gap between consecutive pulses (Pulse Distance Modulation).
The timings of the pulses/gaps will be very fast; usually in the region of 400 to 2000 microseconds. That means it's probably too fast to try to detect them using repeated calls to digitalRead(). Instead, there is a core Arduino function called pulseIn(). When it's called, it will wait for a pulse to arrive on the specified GPIO pin. It will then return the approximate length of the pulse. You can detect high pulses for PWM, or low pulses for PDM.
Precise timing values will vary considerably, so you can ignore small variations. The key is to categorise each pulse as short or long, corresponding to a binary 0 or 1. A good starting point is to consider anything below 1000 usec as short, and everything else as long. Check what timings you actually receive though, and adjust that value accordingly.
Call pulseIn() repeatedly, storing each result. Keep going until no more pulses arrive (you will need to give it a timeout after which it gives up waiting, e.g. 10,000 usec or more).
Your TV remote will output a unique sequence of short/long pulses for each button, typically 32 bits or less (possibly with extra pulses at the beginning/end). All you need to do is figure out which sequence corresponds to each button. You could store that information in a lookup table, and respond accordingly when a sequence is recognised.

A simple IR diode like this can receive raw IR data. There are several chips which are designed to decode these signals, such as this one.
  ----------------
Ir Diode ------------------------------- Ir Decoder

To be more accurate, the TSOP382 is a bit more than just an IR diode; it includes additional electronics (pre-amp). Using a real simple IR receiver diode typically is not enough to just get commands from a TV remote.

The very nice thing about the TSOP382 and like others IC's, is that it has AGC amplifiers built in. Which accommodate a large dynamic change in amplitude, related to distances. Hence it works close and far away. DIY with discrete components gets messy(poor cost vs benefit ratio), as the IR energy drops very fast with distance.

I used TSOP1738 which is easily available at cheap price and I recorded values from more than 10 remotes and it worked very well.
Here is a file which contain recorded values of a Videocon DTH setup box's remote


text:
What's the best way to put in a database sensors data's
I have not already started to try but I'm a good webmaster and I'm just asking which way is more suitable for sending and keeping data from sensors and I/0 state in a database.
Here are some points:

Post versus get
MySQL or others types
Security layers
Graphics render of data's (google API?)
PHP, ruby, JavaScript...
Able to send data request's to Arduino's
Ethernet shield, wifi, I2c ???
Access via Android app...

Anyway, the goal here is to know pros and cons of integrate all my Arduino through database.

This is really vague, and really only tangentially related to arduinos at all.

It depends on your skills and what you have in your Arduino "box".
Let's assume you have an ethernet or WiFi shield.
I would go with a PHP script (I'm a PHP dev, but any language will fit) that accepts POST requests sent by the board and store them in a SQLite db.
Why SQLite instead of MySQL? Well, it's just a matter of data portability. You copy the SQLite file or send it via email and you're done: there are plenty of clients out there to read your db, in *nix based machines is frequently integrated in the OS.
MySQL requires a sort of "infrastructure" to be written/read.


text:
What are the AREF, IOREF, and the unlabeled pin next to IOREF on the Uno R3?
There are some pins on the Arduino which I haven't been able to find out anything about:

IOREF
AREF
An unlabeled one next to IOREF

What are they?

AREF:
This is the voltage reference analog-to-digital converter (ADC). It can be used instead of the standard 5V reference for the top end of the analog spectrum – for example, if you wanted to use the ADC to monitor a signal that had a 0-1.5 volt range you could get the full scale of the ADC by connect AREF to a 1.5V signal. DO NOT CONNECT A SIGNAL OUTSIDE THE 0V TO 5V RANGE!
Note that in order for this to work, you must run analogReference(EXTERNAL); before using analogRead(). Also:

After changing the analog reference, the first few readings from analogRead() may not be accurate.

Fore more information, see AnalogReference.
IOREF:
This is a voltage corresponding to the i/o of that board, for example an Uno would supply 5v to this pin, but a Due would supply 3.3v. Sending a signal to this pin does nothing.
Unlabeled pin:
This pin is unused, but is there to ensure compatibility with future products. It is not connected to anything on any R3 boards I have seen.

I agree with possibly using this pin directly from the 5V pin.  My Nano boards do not measure the same on the ADCs as the UNO boards.  It is somewhere below 5V that I get the 1023 reading.  I assumed they were already referenced to 5V but apparently that was wrong.  Thank you for the tip.

@TheDoctor, what happens if you set AREF to say 6

Concerning the AREF pin, you have to remember that the Arduino comes with a 10bit ADC (Analog-Digital-Converter), which converts incoming voltages between 0V and 5V to integer values between 0 and 1023. This results in a resolution of roughly 4.8 mV.
If a sensor only delivers a lower maximum voltage, it is resonable to apply this voltage to the AREF pin, just in order to obtain a higher resolution.

analogReference();

I agree with possibly using this pin directly from the 5V pin.  My Nano boards do not measure the same on the ADCs as the UNO boards.  It is somewhere below 5V that I get the 1023 reading.  I assumed they were already referenced to 5V but apparently that was wrong.  Thank you for the tip.  Upvote.

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


text:
How do I connect a PS4 controller connected to an Arduino that's connected to a laptop to another Arduino?
My high school is entering an ROV competition and for next year's competition we want to try and set it up so that we can control it using a PS4 controller. I have done research and found this shield for Arduino and this library that allows you to connect it to an Arduino. I plan to then connect the Arduino to a computer via USB and then send each button press to a Processing program via serial. Would it then be possible to send this from Processing to another Arduino out of the laptop? I'm just wondering how feasible this project is.
We initially had just a single Arduino at the top with the Ethernet shield and took inputs from standard joystick potentiometers. We want to add in using the PS4 controller this year for easier control. We found the USB Host Shield that gives us that capability, but uses the same pins as the Ethernet shield. So we added another Arduino, connecting the laptop as the bridge also allows to have a GUI. The Ethernet is wired, by the way. We need the laptop, it's not just for a bridge.

this is possible, but the processig bridge can add a lot of delay if not correctly handled, also wifi has a low range, almost 100m by default hardware.
zigbee module has better range (xbee pro are up to 1km) and are microcontroller friendly, you use the as you are using a serial, they will hide their complexity once you set them up, and this can be done by PC.
That mens less code, that mena less error and more ram/flash/cpu so you can do a smarter robot :)
zigbee use the serial protocol to communicate, exactly as you do with the pc. Also arduino can use, with the library SoftSerial, any pin as Serial. So you can keep the HardwareSerial to communicate with pc, and any 2 free pin to communicate with the xbee. So you can use the arduino stand alone, only with the controller, and when needed connect the pc. Then arduino can act as a bridge between xbee and pc, so pc can excange data with the rover. But even without pc your project will be fun.
The same apply for bluetoot or 400/800mhz rxtx module, but not for wifi shield

One Arduino needs to talk to the computer and the other at the same time. That's not practical with the way it's set up on most boards. The OP would need another UART connection, even so the Xbee and the USB to UART chip use the same pins on all standard boards.

As far as i understand the op use the pc as bridge, so if arduino is indipendant, pc is not needed animore. Also the controller will be more portable

We initially had just a single Arduino at the top with the Ethernet shield and took inputs from standard joystick potentiometers. We want to add in using the PS4 controller this year for easier control. We found the USB Host Shield that gives us that capability, but uses the same pins as the Ethernet shield. So we added another Arduino, connecting the laptop as the bridge also allows to have a GUI. The Ethernet is wired, by the way

Xbee uses serial pin, and using the official SoftSerial lib you can use any pin as serial rx/tx. No double arduino, no pc, but hooking up a pc, and using arduino as a bridge between pc and xbee, is a way better.

The Xbee still isn't ideal. Yes, with software serial you can use two different serial ports, but most Xbee shields are hard wired for the two pins used by USB, causing a conflict. Also, SoftSerial isn't ideal or simultaneous: the OP should use AltSoftSerial. Hmmm... I guess you could hard wire it to the board and use AltSoftSerial. Can you please edit your answer?

AltSiftSerisl is not needed unless he does have particular problem(premature optimization..), it will also use a timer that maybe will be needed on pwm (on the rover side). the sparkfun's shield usr digital 2 and 3 by default(switchable with hardwareserial). Also note the solution was presented for xbee, but as noted it can be used with any RF transciver that has a serial interface, like bluetooth

AltSoftSerial is much better suited for this IMHO. Softserial works best with only one serial port operating at one time, where AltSoftSerial is ideal with multiple ports at the same times.

he use hardwareSerial] SoftSerial, never had a problem with that setup, even on high baudrate. SoftSerial may be a problem when using taht one SoftSerial, because it can listen only one port at time, but this is not the case.

This project is very simple. As I understand it, this is your setup:
+–––––––––––––––––––––––––––––––––––––––––+
|                                         |
|  Arduino 1-––––––––––-PS4 Controller    |
|  |                 (W. Shield attached) |
|  |USB                                   |
|  |                                      |
|  Computer                               |
|  |                                      |
|  |[Wireless]                            |
|  |                                      |
|  Arduino 2                              |
|                                         |
+–––––––––––––––––––––––––––––––––––––––––+

Made with ASCIIFlow
If you have a very small range (I'd say 10-20 feet max), I recommend using Bluetooth. The HC 06 Bluetooth module looks like a good choice. There's also a less powerful HC05 if I remember correctly. I had one once but accidentally destroyed it before I could connect with a bad soldering job :). The one linked on Amazon luckily comes with a "backplane" already soldered so you just need to attach 5V, GND, and the TX/RX pins to the Arduino, accordingly. Then, you can select the BT module (wherever it appears on your OS; search online for this) and then you can connect to it and add the password 1234. After that, it should function like a normal COM port.
You would connect this to the HC06 to Arduino 2, and wirelessly the HC06 to the computer. The computer would then be connected to Arduino 1, who would receive the PS4 signals, with the shield. You would use Processing to receive the PS4 signals and to send data to the second Arduino board. I'm not an expert on Processing, but I found this serial library.
I do not recommend using Xbee because one Arduino needs to talk to the computer and the other at the same time. That's not practical with the way it's set up on most boards. The OP would need another UART connection, even so the Xbee and the USB to UART chip use the same pins on all standard boards.


text:
Is there a limit on how much current a pin can sink?
I've been experimenting with an 8x8 LED matrix controlled by an Arduino Uno. As I think is typical, the matrix uses a common anode for each row, and a common cathode for each column.
At the moment, I've got all the matrix pins connected directly to IO pins on the Uno, and I haven't had any problems lighting the LEDs one-by-one. Going through the whole matrix like this makes updates a little slow though, meaning the LEDs aren't as bright as I'd like.
As far as I know, I can't safely light up an entire row at once, because an individual pin on the Uno isn't capable of sourcing enough current to drive 8 separate LEDs at the same time (requiring at least 10mA each to be bright enough).
It occurred to me that the reverse might be safer. If I light up an entire column at a time, then each pin only has to source enough current for one LED, which should be no problem. However, it relies on one pin potentially sinking the current from all 8, totalling at least 80mA.
Is this possible, or am I going to fry my board?

What exact display are you using (datasheet) and are you using series resistors with it? Maybe you fry hour display rather than your Arduino.

There's no part-number on it so I don't have the exact datasheet. I've assumed each LED has a forward voltage of 2V, and am conservatively using 390 ohm series resistors at the moment (while testing). That means I'm driving them at around 8mA each I think.

that should be just fine.

Could you go into a little more detail about what you are doing, please.  The reason why I'm asking is because I want to do the same thing, and I'm a newbie.  I am RTFMing and your question was the highest hit for my search.  I am jeffsilverm@gm4il.c0m.  thank you.

am I going to fry my board?

Pretty likely outcome. Here's why:
The Arduino Uno uses the atMEGA328 microcontroller, which has an absolute maximum rating of 40 mA source or sink per GPIO. Also, the total current through the supply or ground rails (i.e. the total of all current OP wants the GPIO pins to sink, or source) is rated to a maximum of 150 200 mA.
Realistically, the current graphs in the atMEGA328 datasheet do not even go all the way to 40 mA, hence it is safest to restrict the current to perhaps 20 mA total per GPIO.
In other words, whether a GPIO is used as source or sink, the limits remain pretty low, and in practice, should be kept much lower than the absolute maximum ratings. Even below absolute maximum, running a microcontroller to too high a temperature reduces its life expectancy.
Solution:
Use either BJTs, MOSFETs, or some driver IC such as the ULN2003 to actually drive the current through the LEDs.

Where did you find the 150mA max. for the package? I have a 200mA under absolute maximum ratings.

@jippie I goofed :-)

I'm going to steal my answer from when I answered this question on the last arduino SE attempt.

This is a bit complex. Basically, there are a number of limiting factors:
The IO lines from the microcontroller (i.e. the analog and digital pins) have both an aggregate (e.g. total) current limit, and an per-pin limit:

From the ATmega328P datasheet.
However, depending on how you define the Arduino "Pins", this is not the entire story.
The 5V pin of the arduino is not connected through the microcontroller. As such, it can source significantly more power. When you are powering your arduino from USB, the USB interface limits your total power consumption to 500 mA. This is shared with the devices on the arduino board, so the available power will be somewhat less.
When you are using an external power supply, through the barrel power connector, you are limited by the local 5V regulator, which is rated for a maximum of 1 Amp. However, this it also thermally limited, meaning that as you draw power, the regulator will heat up. When it overheats, it will shut down temporarily.
The 3.3V regulated output is able to supply 150 mA max, which is the limit of the 3.3V regulator.

In Summary

The absolute maximum for any single IO pin is 40 mA (this is the maximum. You should never actually pull a full 40 mA from a pin. Basically, it's the threshold at which Atmel can no longer guarantee the chip won't be damaged. You should always ensure you're safely below this current limit.)
The total current from all the IO pins together is 200 mA max
The 5V output pin is good for ~400 mA on USB, ~900 mA when using an external power adapter

The 900 mA is for an adapter that provides ~7V. As the adapter voltage increases, the amount of heat the regulator has to deal with also increases, so the maximum current will drop as the voltage increases. This is called thermal limiting

The 3.3V output is capable of supplying 150 mA.

Note - Any power drawn from the 3.3V rail has to go through the 5V rail. Therefore, if you have a 100 mA device on the 3.3V output, you need to also count it against the 5V total current.

Note: This does not apply to the Arduino Due, and there are likely some differences for the Arduino Mega. It is likely generally true for any Arduino based off the ATmega328 microcontroller.

Thanks for the summary!  It answered my question super fast!


text:
Beat 1 LED light is always on - should turn off
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 11;
const int keyPinR = 10;
int buttonState = LOW;
int buttonState2 = LOW;
int bpm = 120;
int rthm = 1;
/**************************************/
void setup()
{
  Serial.begin(9600);
   for(int thisPin = 1;thisPin <= ts;thisPin++)
   {
 pinMode(thisPin,OUTPUT); //initialize thisPin as an output
 pinMode(8, INPUT);

 pinMode(keyPin, INPUT);
 pinMode(keyPinR, INPUT);
 digitalWrite(keyPin, HIGH);
 digitalWrite(keyPinR, HIGH);
 }

}

/****************************************/
void loop()
{
 buttonState = digitalRead(keyPin);
 buttonState2 = digitalRead(keyPinR);
 if(buttonState==LOW){
 ts++;
  if(ts==6)
   {
    ts = 2;
   }
  }
 if(buttonState2==LOW){
  rthm++;
    Serial.println(rthm);
  if(rthm==5)
  rthm = 1;

  }
  for(int thisPin = 1;thisPin <= ts;thisPin++)
  {

  for(int r = 1; r<=rthm; r++){
   bpm = pulseIn(6, HIGH);
    digitalWrite(thisPin,HIGH);

    pinMode(13,OUTPUT);

    if(count == 1&&r==1)
    tone(13,1500,40);
    else if(r==1)
    tone(13,1000,40);
    else
    tone(13,500,40);
    delay((bpm-52)/rthm);

    digitalWrite(thisPin,LOW);
    pinMode(13,INPUT);

   }
    count++;
    if(count >ts)
    count = 1;
    }

   }

This is a metronome project. Each LED represents a beat. However, The LED for beat 1 is always on. It should turn off when it's on a different beat other than one. Is there anything wrong with the code?

Can you clarify which pins you are talking about? You have lots of pin names and some numbers scattered throughout the code. What pin is always on? Pin number.

You code is very difficult to read, probably because of the pasting, but why do you set pins as inputs and then write to them.  Also why do you set pins mode 4 times?

You are using PIN1 as an output pin and you are writing data to the Serial interface.  The serial interface uses pin 1 and 0.
Change lowestPin to 2 and ts to 5 and it will work.


text:
Arduino output pin from 5V to 3.3V
I just have a question regarding Arduino output-pins and Voltage divider, because I am getting other results than what my calculations are giving me.
I have measured the output-pin (from the Arduino) at 4.74V, according to my caulculations I will have and output voltage of 3.39V, with R1 = 4k ohm and R2 = 10k ohm, but when I use my multimeter to measure I read a voltage of 0.97V.
I have tested with a 9V battery, measured to 8.72V. With the same resistors, the calculations gives me 6.23V as output, when I use my multimeter I can read a output of 6.21 which I consider as ok.
So my question is, why is my output from the Arduino only 0.97V with the voltage divider?
For information: I am using Arduino OSEPP Uno R3 Plus.
Hope someone can give me helpfull information.
***************************************update********************************************
My code:
int echoPin = 7;
int trigPin = 6;

int SignalPin = 10;

void setup(){

  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);

}

void loop(){

  float distanceCentimeters;
  int pulseLenMicroseconds;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(20);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);

  pulseLenMicroseconds = pulseIn(echoPin, HIGH);

  distanceCentimeters = pulseLenMicroseconds / 29.387 / 2;

  if(distanceCentimeters <= 35 && distanceCentimeters >= 10){

      digitalWrite(SignalPin, HIGH);

  } else {

      digitalWrite(SignalPin, LOW);

  }

  delay(400);

}

Image of the setup (not with Raspberry Pi).

4kohm is a strange value. Are you sure about it?

Are you sure the Arduino pin is actually driven as an output, rather than being an input with the internal pull-up active?  Your measured .97 V could be a result of your resistive divider being fed through about 35K ohms of internal resistance, which is a quite plausible value for the effective resistance of the "weak" internal pull-up feature.  You can tell by measuring the voltage at the high side of R1 - with an output, this should still be close to 5v, but with a pull-up it will may be only slightly higher than the low side of R1.

I assume you are planning to connect to something using 3.3V. A resistive divider is a poor solution. It may be OK for a high impedance connection, but you would be better to use other solutions e.g. Series resistor and diode clamp.

Thank you guys for answering and giving useful information! I have updated the post with my code and a picture of the connection. Thought that would be more helpful. I have measured the R1, and its high side is slightly higher than the low side.I am going to connect it to a Raspberry Pi, where the GPIO pins have a tolerance of 3.3V.

If the high side of R1 is only "slightly" higher than the low side, then you do not have the pin configured as an output.

Your code does not configured SignalPin as an output, but only trigPin.
As already explained in comments, your observed voltage is due not really to the voltage divider you constructed, but rather one formed by the "weak" internal pull-up resistance and your external resistors.  From your measurement, it appears the value of the weak internal pull-up is about 35K, which is within the range of expectations.  That and your 4K external form the top of the divider (39K) while your 10K forms the lower half, yielding about a fifth of the supply voltage.
In some versions of the Arduino library, writing to an input pin enables and disables the internal pull-up resistor, so you could have observed your program seeming to control the pin - but at minimal drive strength.
To get the desired behavior, you merely need to add
pinMode(SignalPin, OUTPUT);

I got one more question, and I don´t expect an answer since it´s towards the RPi. I have written a program that should write out a text if the GPIO-pin is high or low. I have tested it with a button an the RPi´s own 3.3V output-pin. When I press the button it changes. But when I use the Signalpin from the Arduino it does not change at all. The pin has 3.24V now, same as I get with the RPi 3.3V pin. Do you have any idea what it could be?

Try putting several seconds of delay after setting the output pin state, to make sure the pi has ample time to see it.  Of course that is excessive, but you could see see if you can use an interrupt mode on the pi.  Note the existence of raspberrypi.stackexchange.com if your challenges become mostly about the pi; right now it's not clear which end the problem is on.

Signalpin from the Arduino would be 5V. How are you giving it to the 3.3V Pi?

That's the purpose of the resistive divider.  In practice, the 4k series resistance will probably do the job by itself, though slew rate will be limited with this high an impedance.

Did not have time to test this before, but now I have. Have set the delay for some seconds, but still nothing happens. The program on the Pi is working fin with the button and using its own 3.3V pin (measuring it to 3.24). I measure the Arduino output-pin to 3.26V but the program is not registering any changes. Have also test with placing a object in front of the sensor so the output stays at 3.26V, but nothing happens. Can it be related to the current?

Not if you measure it as 3+ volts while connected to the pi - that should indicate it is fine.  You do have a common ground, right?

Yes, I use the GND on the Arduino and that is connected to the - on the breadboard. From the voltage divider the ground goes back to - on the breadboard. But when I test the button with the RPi´s own 3.3V output pin I don´t use GND.


text:
do two arduinos that are linked to a common 9v rail and ground still need a common negative connection for a serial tx rx connection?
so that there a 2 wires rather than 3 to connect between the two for purposes of serial communication.  And the same question for 3 arduino megas on a common rail and using serial connections?

All voltages are ground referenced, hence the ground is the only (supply) connection required. Remote modules can be self-powered and signals will still be discriminated as long as ground is connected.

thank you for your prompt reply , the 9v and negative rail are connected for purposes of powering the arduino boards anyway.  I should have asked Do I need an additional connection between the grounds to that provided by the power connection.

If they're using a common ground then their grounds should be already connected.


text:
How to use Induino R3 on Ubuntu 14.04
I have just got Induino R3. I have installed Arduino on my Ubuntu. I tried blink example but it shows error serial port COM1 not found
I think i need to select proper option from serial port. But i can't click on it!
P.S. I am completely new to Arduino

is your user in the dialout group?

@BrettAM Yes it is i did it from http://askubuntu.com/a/146523/283650

does /dev/ttyACM# appear in your filesystem when the arduino is plugged in?

@BrettAM It is working now. I don't know how but as soon i upgraded Ubuntu from 14.04 to 14.10 is started working!! BTW thanks for help :-)

Not 100% sure of the specific differences between your board and a normal Arduino[clone], but I've never seen serial devices referenced in Ubuntu via COM# labels(Granted I've only used or needed to use serial type devices in the last year, so I could be a bit under experienced).
Anyhow, usually I find serial devices available at /dev/ttyXXX. On my Lubuntu 14.04 installs, my USB connected Arduinos all show up as /dev/ttyACM#. I have an FTDI programmer I usually use on wifi routers which generally shows up as /dev/tty#.
Rule of thumb in Linux, everything is a file somewhere.

I did not get how to fix it from this answer

Did you by any chance, download the Windows version of the Arduino IDE and install it under Wine? Then I would expect it to seek a COM# serial port. In which case you will have to create a symbolic link from the relevant /dev/ttyUSBx to COMx for your Arduino IDE to work.
The right way is to download the Arduino for Linux tar.gz file and extract it to a path of your choice in your Home folder.

I upgraded Ubuntu version 14.04 to 15.04 and now it is working fine!


text:
Responding to a broken laser beam?
Firstly, I must apologise as I'm a complete noob but the Arduino kits / lego pieces are fantastic and I can't stop tinkering.  Unfortunatley my knowledge does not match my passion.
I picked up a laser from Amazon: FamilyMall(TM) KY-008 Laser Transmitter Module 650nm 5V Diode For Arduino AVR PIC.
I'm wondering what the middle pin is good for and if I can somehow manage to detect and respond to the beam being broken?
Thanks for looking. :)

http://www.linksprite.com/wiki/images/thumb/1/1a/KY008.png/300px-KY008.png . Middle pin should be 5v, so I think you miswired it. Signal I'd guess is kind of like an on/off switch.

@Gerben - I don't think it's of the highest quality, the '-' labelled pin is VCC and the 'S' pin is gnd.  Connected this way results in a functional beam.  I suspect the manufacturer is a troll :)

Without a data sheet or the device on hand not sure what the middle pin is used for.  On the topic of detecting a broken beam the item you purchased is purely an emitter, in order to detect the beam being broken there are two main ways, using a photodetector on the "opposite end" of the beam but this means having wires trailing the same path as the laser beam, alternatively you could mount a mirror where the beam lands and reflect it back to a photodetector mounted close to the laser diode.  You would them use the arduino to detect the state of the photodetector.

thank you!  That's exactly what I wanted to know.  I'll look into picking up a photodetector, assuming they're not mega expensive and continue playing.  thanks again!

can I ask if you'd mind looking at this item: http://www.amazon.co.uk/Generic-TCRT5000L-TCRT5000-Reflective-Infrared/dp/B00C0P98C4/ref=sr_1_2?s=electronics&ie=UTF8&qid=1429054085&sr=1-2&keywords=photodetector and saying if you think that this would be more suitable instead of buying the separate photodetector you mention

@SteveGreen That item you linked is fine if you want to detect paper, card or some other reflective material at a maximum distance of 12mm. If that's not what you want to do, then it's not suitable.

thanks @RogerRowland.  I was mainly jsut trying to mess around with setting off a buzzer if a door was opened or something along those lines.  My 'plan' is to play with automation stuff but I'm waiting on a ton of stuff to be delivered and might have bought a lot of 'bit' that are not neccesary but still fun to play with and learn how the arduino etc works :)

Sorry took so long to see your follow up, I assume you have found it to be a fairly powerful laser so you could use the mirror trick over quite a distance.  I looked this up for you to give you some ideas to get it done on the cheap:  http://www.instructables.com/id/Arduino-Laser-Tripwire/

oh and just in case it's still relevant no the items you linked to would not work.  They have a filter that selectively blocks "all" wavelengths of light apart from the one its interested in ie in this case 950nm .  Your laser on the other hand produces light in the 650nm wavelength and in theory would be blocked by the filter on the photodiode.  If you looked you may find one with a 650nm filter which would be perfect for your application.


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

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

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

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

Circuit Operation:
Suppose the following conditions hold.

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

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

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

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

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


text:
How do I make a atmega 32u4 mp3 player?
Is there a way to use the atmega 32u4 breakout board to make a mp3 player without the mp3 shield?

I don't think it has enough CPU power to decompress mp3. I think wav-files playback is possible.

You don't.
A basic ATmega lacks the computational (and perhaps memory also) resources for mp3 decoding.  And even if you do decode to a linear PCM format, you do not have a good way to output it.
You can playback linear PCM data by pulse width modulating a pin, but the limited clock rate will result in limited resolution, and thus poor fidelity.  You will also end up with a low sample rate, making it hard to avoid audible artifacts.
The situation can actually be somewhat better with an ATtiny85 - still no MP3 decoding of course, but you can clock the counter/time block at a higher rate and so playback PWM audio with higher fidelity, provided you are willing to tolerate the inaccuracy of the onboard clock oscillator that may shift your audio frequencies by a small amount.
If you want to do MP3, you will need either a more powerful processor (often no more expensive than the one you have, and typically cheaper as a module than anything "-duino"), or else a dedicated function chip to act as a coprocessor for that purpose.


text:
Using a library of sleeping with a combination of the WD and a physical INTERRUPT
I would like to use one of the nice libraries like :

JEELIB
ENERLIB
SLEEP_N0M1
NARCOLEPTIC
ADAFRUITSLEEPY_DOG
LOW_POWER_MASTER

But to use a X second interval of sleeping and in the same time to enable the option of an Interrupt on pin2 that will get me out of all this sleepy mode vector if there will be interrupt ! which library is better and easier for this situation?
when I want more then 8 second , what is the mining of doing 2x8s when they wrote it in some of those libraries -what should it mean to do ?
Is there an option to enable the interrupt for a wake up from the sleep not only by a LOW_mode but also by a CHANGE_mode of the pin2 ??

Thank you very much in advanced @!

"Best" is completely subjective. I've used Narcoleptic myself. it's easy to use and somewhat limited. For the needs of my project, it served well. You'll need to review the libraries' source code and descriptions to decide which library will best serve your application.
The Watchdog timer has a maximum interval of 8 seconds. To sleep longer, you'll need a routine that counts enough 8 second sleeps, plus lesser sleep periods, to make up the total sleep time you want. There are other timers you can use, but not in Power Down sleep mode.
See section 10, "Power Management and Sleep Modes" of the ATmega328p datasheet (or the datasheet for the chip your Arduino uses). There is a table of wake-up sources for each sleep mode. It says that, except from Idle mode, only a level-triggered interrupt can wake the chip. But note that section 10.5 says a pin-change interrupt can wake the CPU. It appears that either kind can wake it but "the required level must be held long enough for the MCU to complete the wake-up to trigger the level interrupt." It does not mention the (obviously transient) pin-change interrupt. You may need to experiment.

Update:

...I cant get a sleep for more than 8 second but I can only get to a sleeping mode twice and by that to get almost a 16 second of sleeping ?

Yes, the longest Watchdog timer period is 8 seconds.

I still didn't understand if there is an easy possible to get into a sleep with a routine periods of WD wakings and in the same time enabling a physical interrupt on pin2 that works parallel ?

From my reading of the datasheet, yes, you can use both timers in parallel. But it wasn't clear to me whether a pin-change can both wake the CPU and cause an interrupt (that is, vector into your interrupt routine). A level-interrupt can, if the level is held long enough (I believe they said 4 CPU cycles would be required).

So if I right for question 2. the answer is that I cant get a sleep for more than 8 second but I can only get to a sleeping mode twice and by that to get almost a 16 second of sleeping ?

I still didn't understand if there is an easy possible to get into a sleep with a routine periods of WD wakings and in the same time enabling a physical interrupt on pin2  that works parallel ?

Tank you very much for your answers my friend !


text:
How to access multiple SPI interfaces on Arduino
I have worked on SPI devices connected with an Arduino one at a time. How do I work with two different SPI devices at the same time?

Assuming you just want to connect two SPI slave devices to the SPI bus and use them in a mutually exclusive way under software control, with the Arduino as the master, then you just need to make sure you use a different pin for the slave select (SS) on each SPI device.
When you want to talk to one slave, you hold its SS low and drive the other high. Do the opposite to talk to the other slave.
There are some devils in the detail using multiple slaves, and these are explained in more depth here, but in general, it's quite common and OK to use more than one SPI device as a slave.
This blog post will give you more information and is a good place to start reading.

By design you have to connect MOSI/MISO/SCK in parallel for multiple slave except for the SS. You could use shift register circuit/IC to use a daisy chain connection on slave for SS line.


text:
ISR executes even though an interrupt is not triggered
I am trying to implement a function queue scheduling system. INT1 is connected to a button and int1task causes an LED to flash.
typedef void (*funcptr)(void);
TPrioQueue *queue = NULL;

void int1ISR() {
  if (debounce(&int1time)) // Checks if the interrupt is caused by switch bouncing
    enq(queue, (void*) int1task, 1);
}

Next, I execute the function in loop() by:
typedef void (*funcptr)(void);

void loop(){
  funcptr func = (funcptr) deq(queue);
  if (func != NULL)
    (*func)(); // Stuck in a loop
}

For some reason, the LED keeps flashing even though I have not pressed the button. Why does this happen?
When I remove the line below, the ISR works properly.
enq(queue, (void*) int1task, 1)

The relevant sections of the code:
int debounce(unsigned long *debTimer) {
  unsigned long tmp = *debTimer;
  unsigned long currTime = millis();

  if ((currTime-tmp) > 500){
    *debTimer = currTime;
    return 1;
  }
  else
    return 0;
}

// Flashes LED at pin 6 five times at 2 Hz
void int1task(){
  for(int i=0; i<5; i++){
    digitalWrite(6, HIGH);
    delay(250);
    digitalWrite(6, LOW);
    delay(250);
  }
}

void setup() {
  pinMode(6, OUTPUT);
  attachInterrupt(1, int1ISR, RISING);
  Serial.begin(115200);
}

Code I used for the queue
Here is the schematic I am using:

If debounce() calls millis(), then it will not work, as millis() do not change within an ISR. Can yoi show the code of debounce()?

@jfpoilpret I have edited the code to call millis() only once. Similar to https://community.spark.io/t/how-to-track-debouncing-in-an-interrupt-function/6918

I don't see any code that toggles the led. I don't see any code initializing the interrupts.

Could you please also show the code of int1task? Without it it may be hard to diagnose your issue.

It seems the int1task is never removed from the queue, which would explain it's running forever. Where do the enq and deq come from? How was queue variable declared?

@jfpoilpret enq and deq are declared in a separate file. The queue is part of a struct called 'TPrioQueue'. I declare it TPrioQueue *queue = NULL

@jfpoilpret I do not understand why int1task is not being removed from the queue? I am dequeue-ing it in loop()

I suspect a concurrent access problem (by loop() and the ISR). I think you should post the code of enq, deq and also the TPrioQueue or a link to the code if it is a 3rd-party library.

@jfpoilpret code for the queue

The queue has to be initialized with makeQueue().

May be just a matter of style, but you may just write if (func) func();.

Your snippets are still lacking a few important lines of code: we would like to see the declaration of all variables: queue, int1time. Also, did you check what @EdgarBonet mentioned in a previous comment, ie initialize queue with makeQueue()? That seems a real important point here!

I just tested your sketch on my Uno: it works as expected provided the queue is properly initialized with makeQueue().

@EdgarBonet The circuit works after adding makeQueue()

After checking the queue functions that you use in your sketch, I see there is no protection against concurrent accesses in the enq and deq functions, which is a must-have if you use any of these functions from within an ISR.
I would suggest the simplest changes to these functions as follows:
void enq(TPrioQueue *queue, void *item, int priority)
{
    TPrioQEntry *newEntry=(TPrioQEntry *) malloc(sizeof(TPrioQEntry));

    if(newEntry != NULL)
    {
        newEntry->item=item;
        newEntry->prio=priority;
        newEntry->prev=NULL;
        newEntry->next=NULL;

        // Protect against concurrent accesses starting here
        uint8_t sreg = SREG;
        cli();
        if(queue->head==NULL)
            queue->head=newEntry;
        else
        {
            // Find insertion point.

            // First special case: Item at head has lower priority
            if(queue->head->prio > newEntry->prio)
            {
                // Insert item at the start of the queue.
                newEntry->next=queue->head;
                queue->head->prev=newEntry;
                queue->head=newEntry;
            }
            else
            {
                // Find your insertion point
                TPrioQEntry *trav= queue->head;

                while(trav->next!=NULL && trav->prio < newEntry->prio)
                    trav=trav->next;

                newEntry->prev=trav;
                newEntry->next=trav->next;
                if(trav->next != NULL)
                    trav->next->prev=newEntry;

                trav->next=newEntry;
            }
        }

        queue->itemCount++;
        // Protect against concurrent accesses stops here
        SREG = sreg;
    }
}

void *deq(TPrioQueue *queue)
{
    // Protect against concurrent accesses starting here
    uint8_t sreg = SREG;
    cli();
    // Return NULL if queue is empty
    if(queue->head == NULL)
    {
        // Protect against concurrent accesses stops here
        SREG = sreg;
        return NULL;
    }

    void *ret=queue->head->item;
    TPrioQEntry *tmp=queue->head;

    if(queue->head->next!=NULL)
        queue->head->next->prev=NULL;

    queue->head=queue->head->next;
    free(tmp);

    queue->itemCount--;

    // Protect against concurrent accesses stops here
    SREG = sreg;

    return ret;
}

The above code did not work, the LED still kept flashing

If this still doesnot work, I suspect you may have some bad wiring or interferences somewhere in your circuit. Could you show a clear picture of your circuit? A schematoc would also be nice to have.

The simplest change would be to #include <util/atomic.h> and call deq() from an ATOMIC_BLOCK.

@jfpoilpret [schematic] (https://www.dropbox.com/s/51f8174815zycrg/schematic.pdf?dl=0)

Isn't declaring some of the variables volatile required for this to work reliably?

I don't think so, because the only variables here are pointers; those pointers are not chnaged only the content they point to.

Although you did not clearly mention nor show your wiring, it is possible the problem comes from here.
Barring real concurrency issues with your queue implementation, which I already mentioned in another answer, for which fixes have to be implemented anyway, there are two potential wiring problems in your circuit:

You use INT1 interrupt; that means you must connect your button to PIN 3 for a UNO, any other pin won't work.
You did not specify pinMode(3, INPUT_PULLUP) in your setup(), which means you MUST use an external pullup resistor to force a HIGH value, and connect the other pin of the button to GND (or conversely: put a pulldown resistor and wire the other pin to 5V); otherwise, while the button is left unpressed, you will have a floating input, which means its value will vary randomly between HIGH and LOW, triggering your int1ISR many times when you don't expect it.

The simplest way to solve point 2 (floating input) is to use internal pullup resistors:
void setup() {
  pinMode(3, INPUT_PULLUP);
  pinMode(6, OUTPUT);
  attachInterrupt(1, int1ISR, RISING);
  Serial.begin(115200);
}

and connect one button pin to Arduino PIN 3, and the other button pin to GND.
That will remove floating input and its consequences.

ISRs have flags, typically an enable flag and a pending flag.
The enable flag needs to be set true for the interrupt to occur at all.
The pending flag is set when the interrupt event occurs.
Within the interrupt function, the pending flag must be cleared,
otherwise the the interrupt function will immediately be executed again (and again and again and ...)

AVR resets the interrupt flag once the ISR returns.

I am relatively new to arduino. Could you elaborate more about the flags? Are they like cli() and sei()?

My mistake, INTFn is cleared when the ISR is executed.


text:
How to use output from Arduino in C++ code?
I am a complete novice in Arduino and moderately experienced with the language C++. What if I want to use the output from the serial monitor in C++ code in real time?
Also how can I write to the serial monitor. Which libraries are available for this? Also please give me links to sites where I can learn more about this topic. I am using Arduino Uno.

Which Operating System are you using?

@PeterR.Bloomfield Windows 7 32 bit

This question appears to be off-topic because it is mainly about C++, not Arduino.

@TheGuywithTheHat - unfortunately on any other SO site the question would likely be instantly flushed here without a read for merely mentioning "Arduino".  I would agree that the question pertains to embedded systems in general, but the poster may not know that - part of what answers may need to do is explain what the Arduino Serial Monitor is doing and that the solution is likely not to claim data from that, but rather get data from the same source it does.

@ChrisStratton I would love to learn more about what you are saying. The problem with the internet is there it's too much information and funding something useful is difficult unless you know what you ate looking for... So if you can suggest things I can read to increase my knowledge about arduino or embedded systems in general please do so. Also I would like to learn more about the hardware side of things (For instance what it means to connect a device serially to the computer) and a little more about how it works. Please suggest good sources if possible.

Also please keep in mind my knowledge about arduino or embedded systems in general is practically null. All I have done so far is tweaked the example codes.

Check the modified code in my answer

Unfortunately, C++ doesn't have native support for serial I/O.
You could use the Windows API directly if you're feeling adventurous. It can be a little complicated to get to grips with, but not insurmountable. You can get basic information about it here. There's an example of using it with Arduino here.
As an alternative, you could use a 3rd party library. This one looks good, although I haven't actually used it myself.

#include <windows.h>
#include <string>
#include <stdio.h>
#define ARDUINO_WAIT_TIME 2000
using namespace std;

string portNumber;
HANDLE hSerial;
bool connected;
COMSTAT status;

bool connectPrinter(char *portName){

    //Connects to the port.
    hSerial = CreateFileA(portName,
    GENERIC_READ | GENERIC_WRITE,
    0,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

    if(hSerial==INVALID_HANDLE_VALUE)
    {
        if(GetLastError()==ERROR_FILE_NOT_FOUND){
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);
            return false;
        }
        else
        {
            //If port is in use by another program or did not closed previous process.
            printf("ERROR!!! \n");
            CloseHandle(hSerial);
            return false;
        }
    }
    else
    {

        DCB dcbSerialParams = {0};

        if (!GetCommState(hSerial, &dcbSerialParams))
        {
            printf("failed to get current serial parameters!");
            return false;
        }
        else
        {
            // Set Serial Port specifications.
            dcbSerialParams.BaudRate=CBR_115200;
            dcbSerialParams.ByteSize=8;
            dcbSerialParams.StopBits=ONESTOPBIT;
            dcbSerialParams.Parity=NOPARITY;

             if(!SetCommState(hSerial, &dcbSerialParams))
             {
                printf("ALERT: Could not set Serial Port parameters");
                return false;
             }
             else
             {
                 connected = true;
                 printf("Connection Successful for :%s !!! \n" ,portName);
                 //Wait 2s as the arduino board will be reseting
                 return true;
                 Sleep(ARDUINO_WAIT_TIME);
             }
        }
    }

}

int readData(char *buffer,unsigned int nbChar){

    DWORD bytesRead;
    DWORD dwCommModemStatus;

        //Set the type of data to be caught.(RXCHAR -> Data available on RX pin.)
        SetCommMask (hSerial, EV_RXCHAR );

        while (hSerial != INVALID_HANDLE_VALUE)
        {
          // Wait for an event to occur for the port.
          WaitCommEvent (hSerial, &dwCommModemStatus, 0);

          if (dwCommModemStatus & EV_RXCHAR )
          {
                //unsigned int toRead;
                //ClearCommError(this->hSerial, &this->errors, &this->status);
                do
                {
                  // Read the data from the serial port.
                    ReadFile (hSerial, buffer, 1, &bytesRead, 0);
                  // Display the data read.
                      printf ("%s" ,buffer);

                } while (bytesRead > 0);
          }
        }
    //}
    //If nothing has been read, or that an error was detected return -1
    return -1;
}

    int main()
    {

        char* buffer = new char[32768];
        int nbChar= 32768;
        string str="COMx"; // Use your port number to connect

        char * writable = new char[str.size() + 1];
        std::copy(str.begin(), str.end(), writable);
        writable[str.size()] = '\0';

        connectPrinter(writable);
        delete []writable;
        readData(buffer,nbChar);
        return 0;
    }

try this one, it should work. Comment below if it does not work. You might reset Arduino to read data in method void setup() in Arduino code. I recommend you to use C#, Java or Python for efficiency.

What about writing data... Also please upload arduino sketch if possible! Your answer is really good , sorry i cant upvote as it requires 15 rep!

@Peter has already posted library links.
I recommend that you use Node.js (node-serialport) or Python (serial), which have excellent native serial support.
Both of these use C++ internally to communicate over Serial (Serial.h).
Try going through the code Node.js uses internally, and if you are willing to write that much, by all means use the library.


text:
Malloc with Objects in Arduino libraries
My understanding of using dynamic memory on the arduino is that new/delete are not available, only malloc realloc and such C functions, as mentioned here:
C++ & the AVR
I am creating a library that defines an object type that needs to contain a dynamic list of other objects. In C++ I would define it something like this:
class Container
{
std::vector<otherObjectType> otherObjects;
};

which obviously does not work in the arduino without the C++ standard library.
My next choice would be to create a dynamic array using new, ie
otherObjects = new otherObjectType[3]
{
    {   (arguments to constructor...)
    },
    {   (arguments to constructor...)
    },
    {   (arguments to constructor...)
    }
};

But this does not work as well, since new is not supported...
finally I could try to use malloc as laid out here, but that also wont work without new.
I am wondering if I should just rewrite everything as structs, since that wont require me to worry about whether the constructor for the object was called when the memory was allocated in malloc.

new actually does work in arduino. it is defined in arduino/hardware/arduino/avr/cores/arduino/{new.h, new.cpp} using malloc. It is not part of avr-libc though (which your link concerns) and has not always been added by arduino.
Both of these work for me:
namespace{ //namespace to deal with .ino preprocessor bug
    class foo{
    public:
        int bar;
        foo(int a){
            bar = a;
        }
    };
}
...
//using new
foo *a = new foo[3]{{1},{2},{3}};

//How I would probably do this with malloc
foo *b = (foo*) malloc(sizeof(foo)*3);
b[0] = foo(2);
b[1] = foo(4);
b[2] = foo(8);

Placement new is not defined right now. I know that copying isn't quite the same, but it should work in most cases.
Of course, if you know exactly how long you want the array to be at compile time, you should probably make it a static/global variable so that you avoid using dynamic memory and the sketch ram usage number will be closer to correct.

Yep, new definitely works. I think my misunderstanding was based off of a really old arduino forum post http://forum.arduino.cc/index.php?topic=2249.0. My mistake


text:
Arduino powering from 9V battery
Yesterday afternoon I have left my Arduino running on a fresh Alkaline 9V battery (+ connected to Vin, - connected to GND). Today morning (16 hours later) the LCD display was no longer visible, and when I measured the volatage, I saw the battery was depleted to my surprise - its idle voltage was only 7 V.
My device is Arduino Uno with LCD 2x16 with LCD backlight and 2 DS18B20 sensors. Is it normal for such device to deplete 9V battery this quick?
I have read an answer to What are (or how do I use) the power saving options of the Arduino to extend battery life? question and I think what I see might be related to this, however I am not sure. If it is, is there some common schematics how to connect Arduino to be powered by a battery efficiently?

I'd try attaching a multimeter and measuring the current from the battery with the whole thing and with the display and sensors disconnected.   Don't try to optimize the arduino if it's something else pulling most of the power.

@bowlofred "measuring the current from the battery" - Will do, hoever I need to buy a new 9V cell first. :)

9V batteries are tiny, only around 500mAh. The LCD backlight alone will kill it within hours.

More radical approach for powersaving: 1. Using TI MSP430 board instead of Arduino; 2. Using non-linear regulator; 3. Using LCD without backlight (like in a calculator).

@bowlofred Whole thing current is 61 mA. With no backlight it is 57 mA, with no LCD and no sensors it is 56 mA.

Power consumption
The Arduino boards use a fair bit of power compared to other embedded systems with similar functionality.
There are three main factors:

The NCP1117 (datasheet) 5V linear regulator in the Arduino UNO
R3 (schematic) has a quiescent current of around 6mA.
The ATMega328P (datasheet) draws around 5mA @ 8MHz and 5V, and probably more than double that at 16MHz.
user2973: The ATMega16U2 used for USB communications also draws approximately 13mA.

LEDs and other peripherals also draw some current. In your circuit, the LCD backlight is probably drawing 4mA as well.
When dropping 9V to 5V via a linear regulator, almost half of the power is lost by the regulator due to its 4V drop. Duncan comments that this nearly doubles the quiescent power draw from 9V as well as the power needed for every mA of 5V, since 4/9ths of the power gets wasted as heat by the voltage regulator. An efficient switching regulator would put out 5V with little wasted energy, effectively reducing the current draw seen by the battery by 4/9ths.
A duracell 9V battery (datasheet) drops from 9V to 7V in around 7.5 hours with a 50mA current draw. Therefore, a rough guess is that your circuit draws around 25mA, which sounds about right based on the description of your circuit.
Note, alkaline battery life is non-linear with respect to current. For very small currents (<1mA) the life of an Alkaline approaches that of a lithium battery.
Getting current down
Here are some tips to get the current consumption down:

Regulator: Replace the regulator with one with a low quiescent current, or better yet, a switching regulator (also with low quiescent current). A switching regulator uses 'pulses' of current and some external inductor and capacitors to give a reasonable steady voltage output. It doesn't waste energy like with the voltage drop of linear regulator and efficiency in the high 90% are possible.

There are buck (step down) converters that take the battery as input, then connect directly to 5V and GND, bypassing VIN and the regulator. This one from Pololu both steps up and down, and has 0.1mA quiescent current.
Alternatively, you could use some 1.5V alkaline batteries, and a boost (step up) converter to get the voltage up to 5V (e.g. this product from Sparkfun). It seems boost converters are more commonly stocked.
Finally, you could buy a rechargeable lithium battery with charging shield. This advantage of this is not having to buy new batteries, and for a tiny bit bigger than a 9V battery the lithium one has much greater capacity. A really cool product is the seeeduino stalker waterproof kit that includes a charging circuit, battery, solar panel and other goodies.

ATMega328P: Rather than using delay for timing and spinning in loop endlessly waiting for something to happen, re-write your code so that it goes to sleep in between sensor reads, etc. There are a few low power libraries out there that use the watchdog timer for periodic wakeup from sleep which are handy. You can get the current consumption of the ATMega328P below 0.1mA during sleep.
LCD: Turn off the backlight, or even the entire LCD. Add a button to the design that the user can push to activate the LCD and have it turn off after a set amount of inactivity.
Peripherals: Most peripheral chips also have a sleep mode that drastically reduces their power consumption. Remove power LEDs and other indicators that are not necessary.
ATMegu16U2: user2973 comments It seems this chip is quite power hungry (user2973). It could be removed to save power and just use the UART instead, but that seems like overkill. There are Arduino Pro boards that are just the bare bones Arduino without the USB interface that could be used instead of the UNO.
Batteries: Other alkaline cells have much greater capacity. For example, a 1.5V AA has over 2000mAh for low currents. Using AA cells plus a boost converter can increase the time before battery replacement. Use D cells (16000mAh) and it will run for quite a while. :D

Summary
With appropriate power supply and coding you can get a reasonable amount of life out of a battery. Using the above principles, I have made an Arduino derivative board that measures a few sensors and stores the readings to an SD card every half a second. It can last for about 4 months on 2 AA batteries, so it is definetly possible to have low power and remain in the Arduino ecosystem.
The chip I used for the low power in my board is the LTC3525-3.3V. It takes an input voltage as low as 0.8V and boosts up to 3.3V and a 5V version is also available. I designed a PCB for this chip as there was no ready-made breakout, and in the datasheet there are reference designs. The main critera for choosing this chip was it still had high efficiency at very low currents. Some other converters need a small minimum current draw.
The biggest consumer of power on the board ended up being the micro SD card. It can vary between 0.1mA and 1.5mA of idle current depending on the manufacturer. I have found Verbatim and Lexar cards to consume the least amount of power. I will this EE.SE question up to date with the results of my micro SD card power consumption tests.

Good thorough answer. Note: the power consumption of the usb to serial atmega16u2 which will be very significant after solving the other issues.

@user2973 do you have an idea of what it might be? I can get the typical characteristics off the data sheet, but I didn't put it in as I don't know if the firmware has any sleeping in it. If it is just running normally it is 12mA @ 5V which is a significant draw.

@geometrikal, how do you power an Arduino with 2 AA batteries? That's only 3 volts, which is below the minimum. Is the power supply you mentioned a buck/boost supply? (Outstanding answer by the way .)

@geometrikal There's no sleeping in the firmware for the atmega16u2. So the consumption should be the typical value - 13.5 mA (max 21 mA) according to my datasheet.

@geometrikal, would you mind posting a link to one of the buck power supplies you mention, like the one from SparkFun? I just did some searching and can't find it. For long life a buck style supply seems critical, since the idle current from a conventional voltage regulator is significant.

@DuncanC I couldn't find one either, I was thinking of the boost converters. I've edited the answer with a link to a pololu one that looks promising. They are also known as step down converters.

@DuncanC: Some AVRs can run on as little as 1.8V, and the ATtiny43U has a built-in boost converter that will let it run on a single AAA.

@geometrikal, you said "...Also when dropping 9V to 5V via a linear regulator, almost of the power is lost by the regulator due to its 4V drop" Doesn't that nearly double the quiescent POWER draw from 9V as well as the power needed for every mA of 5V? (Since 4/9ths of the power gets wasted as heat by the voltage regulator.) Seems like running it off a buck converter like a TSR 1-2450 would be better

@DuncanC yes true! I'll update with your comments.

@DuncanC I have updated with your comments. If you or anyone would like to expand or add on anything, please feel free to edit the answer.

I think an Arduino Uno is not suitable for such projects. Some components on the board draw too many amps, as @geometrikal correctly points out. If you're up to a challenge, I would advise you to take your project to another level and go barebones.
Sparkfun has a good article about how to increase battery life, using an ATmega328 that you also have on your Arduino Uno:
https://www.sparkfun.com/tutorials/309
Look for ways to create a circuit with only the components that you really need, and have your microcontroller sleep as much as possible.

Another option is to look for a hardware (Arduino Clone) that has been designed for that, like this board: https://bitbucket.org/talk2/whisper-node-avr/overview
Combining such hardware with power-saving code techniques you should be able to run projects for quite long time on batteries!


text:
Arduino LED backlight - should PWM be used with transistor or capacitor?
I have implemented a PWM controlled LED backlight for the LCD in my Arduino Uno design. One LCD backlight pin is connected to +5V, the second to the ground via 220 Ohm resistor and MOSFET controlled from a PWM capable D9 pin.
Everything seems to work fine, I do not see any oscillation, but after some reading about PWM I am not sure if I perhaps should connect a 100 uF capacitor to smooth the voltage?
Is the MOSFET even necessary? It seems backlight is drawing about 5 mA - can I perhaps drive it directly from the D9 pin, using the resistor? (It seems another user in Do I need to use a resistor if I am using a potentiometer to control an LED's brightness? is controlling brightness without any of those.)

You don't need the MOSFET, you don't need the capacitor, you do need the resistor.
The pins on your Arduino can deliver up to 20mA comfortably, so in this case there is no need for the MOSFET. However, if you were to replace your backlight with a high power LED, your current setup will work just fine.
Without a capacitor, your PWM is a nice square wave. The cap will, depending on its capacity and the resistor in your circuit, turn that into a more rounded waveform, or very ripply DC. Whichever is the case, it will not benefit the (dimming of) your LED. With some bad luck it will even introduce flickering instead of preventing it!
The reason why you should still use the resistor is to prevent the LED from drawing too much current. Without it, it's simply a game between the LED and the Arduino pin to see who will burn first. Whoever wins, you'll end up with a destroyed backlight or fried Arduino. Adding a component costing a few cents can prevent that.