text:
Connecting a USB 3.0 Flash Drive
Is it possible to connect the nine pins from a USB 3.0 memory drive to the corresponding GPIO pins of the arduino (intel Galileo is what I am using, but it is very similar) and access the drive's memory through the implementation of the USB's protocol? I have searched around and have not been able to get a clear idea on how to do this or if it is even possible.

An arduino has no USB host function for as far as I know

@Handoko The Galileo and Due both do.

@Annonomus Ok, that's new for me. But I'm only familiar with the Arduino Uno, Leonardo and Mega.

If you want to economically hang a large storage device off an Arduino-type board, use an SD or uSD card, which can be bit-banged in software off of arbitrary GPIO pins if no specific controller is available.  You can then insert that card into a USB reader if a different system needs to pre-load or analyze the data on it.

Since this is going to be a long post, I'll post the summary above the fold to save some of you the effort of scrolling...
tl;dr: No, it's not possible to do so with GPIO pins. There is another way to do this, but IDK if the rest of the Galileo will be a bottleneck (and it's pretty pricey). The stereotypical AVR Arduino is simply too underpowered (both from a MCU and amperage standpoint) to host USB 3.0. You need a shield to host USB 2.0, and even with that, I doubt that you can use 2.0 at it's full potential.

Basic corrections/things to note (before I begin):

Note: I'm no expert on the Galileo, I'm just doing this all from what I remember from what I've read in the past. If you spot an error, feel free to post a comment with a little explanation and I'll fix my post. However, I doubt that there will be any major errors, and the overall content (i.e. the tl;dr) should be fine.
These figures are maximum that I'm posting:

Speed: if speed is near maximums, or even 10%, what's the point of 3.0?
Power: you never know with this one, so account for it being near limits, unless externally powered. Still, don't risk it.

If it's a USB thumb drive, you're going to either get a breakout board for 3.0 and/or break open your device and solder wires onto it. Note that there doesn't seem to be a USB 3.0 breakout board (from a very quick search on Google). I'm also concerned that the wires you would use might not be high enough grade for extreme data transmission.
Only 7 of the 9 lines are used for data. The other two are 5V and GND.
On a Galileo, you'll have to use the 5V selection for the IO pins.
On a Galileo, there's a Mini-PCIe port (although I can't seem to find it in the photos myself). You could add a Mini PCIe to USB 3.0 card. However, that will cost you almost $50 to do so, and by that time it might be better just to seek out another solution.
Photo of it:

Ask yourself do I really need the speed?

No: don't waste the money and the headache.
Yes: consider either another platform or buying this product.

Keep in mind that, although it fits, it probably won't be able to get enough power for true USB 3.0 that your disk needs and drivers will be rare. You for sure will want to research this more before shelling out the cash to buy this card.

Galileo doesn't run a full OS, so I'm highly doubtful that there's drivers.

Like I mentioned before, I'm not quite sure about the Galileo supplying enough power... again you need to check into this and maybe add an external voltage regulator (if all the other issues are resolved). USB 3.0 can provide up to 2x the power per port of 2.0, so when I say almost an amp, it's technically almost two amps (although I think at this point you'll just have to remember not to use the second port and call it one amp).

Technical problems:
I stated this before in the post:

The stereotypical AVR Arduino is simply too underpowered to host USB 3.0. You need a shield to host USB 2.0, and even with that, I doubt that you can use 2.0 at it's full potential.

The Galileo has native 2.0 support, so I'd recommend just getting a fast USB drive and using that.
Anyway, think about it: the Galileo can handle roughly 400,000 instructions per second. USB 3.0 can send up to 5,000,000 bits in the same amount of time! Like mentioned before, it is the maximums, but still. AFAIK on the AVR boards it it takes multiple instructions to read one GPIO pin (for some reason I want to say 3, but that seems too low). I'd imagine that it'd be the same situation on the Galileo. I'm not quite sure about the instructions it takes to read a pin, correct me if I'm wrong anyone. Anyway, assume it takes four instructions per pin, and your device only sends 1 Gbps. That's still 1,000,000 times that a pin needs to be read when you can only read 100,000 in that time. Even so, you can't even use the data, nor can you implement a loop or other code that combines bytes to read the data in the first place! Plus, you wouldn't have enough RAM!
I'm not a USB expert, but IIRC it only asks the device for data as needed, but still, that'd be pointless to create your code for this and spend the extra money for 3.0 cables and devices. This paragraph is all from memory, I don't really know; don't cite this paragraph.
Also, you'd have to implement your own code for sending data to/from the device. No such code exists without hardware for 2.0, let alone 3.0.

Conclusion:
It's near impossible to do so, and you'd need a lot of extra parts and have to read up on the USB 3.0 specs. I think it would take a great engineer 50+ years to accomplish this without developing an IC (which would cost money). Do you really need the speed? If not, you can buy USB 2.0 host shields and communicate via SPI. That isn't very fast, but still, it's possible.

Sources:
Info and photos are scattered on the following sources:

http://en.wikipedia.org/wiki/USB
http://arduino.cc/en/ArduinoCertified/IntelGalileo
http://www.amazon.com/StarTech-com-Express-SuperSpeed-Adapter-MPEXUSB3S2/dp/B004NO0LK8

Thank you for the explanation; this project wasn't about getting the maximum speed out of the USB 3.0 but more of a learning experience to see if I could do it. I was planning on pulling the 9 pins from USB drive into GPIOs. But you said this was impossible because of current and voltage. So my question now is would it be possible to do with an external power source? I wanted to write the low level driver code myself as well, now is this also impossible? If not USB3.0, is USB2.0 feasible?

@Akash Although an external power supply would solve some problems, it simply isn't feasible to do direct USB connections. A separate chip is ideal for this, and you can purchase them online. Even so, you'd still have to find the appropriate datasheets and code things like the handshake. This alone would be a huge undertaking, and you'd still need more code to even inference with the USB drive. You can buy 2.0 host shields fairly cheap, but that's really your only option.


text:
Button to optocoupler to fire camera 4 times
Ok, this is my first project where I've not had @forsvunnet close by to help.
I've got a camera connected to an optocoupler, that just fires HIGH then LOW.
I can't get a button working with it, so when I push a button, it fires opto 3 times.
This is my sketch.
 // Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int opto = 12;
int buttonInput = 2;     // the number of the pushbutton pin
int buttonState = 0;         // variable for reading the pushbutton status

// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.m
pinMode(opto, OUTPUT);
pinMode(buttonInput, INPUT);
digitalWrite(buttonInput, LOW);}

// the loop routine runs over and over again forever:
void loop()
{
  buttonState = digitalRead(buttonInput);
  if (buttonState == HIGH) {
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
  } else {

  }

}

Anyone point me in the right direction? It's driving me mad.

What camera are you using? What hardware? Can you provide more information by editing your question? Thanks!

Why do you use digitalWrite() on an input pin (buttonInput) in setup()? Should it be opto instead? Also, do you use a pullup (or pulldown) resistor to force a level on buttonInput when the button is not pushed?

First of all, the loop (if it worked well) would only fire twice. It should only fire when you turn it on/off in a cycle (unless it's a rising/falling edge circuit (i.e. a pull down button/a falling edge interrupt), but I won't get into that). In your code you toggle it twice. The third one? I suspect that your camera only fires when it's given a low signal. This means that, when you set it to low in setup(), it takes a photo. To fix this, switch all the HIGHs and the LOWs for the opto pin.
This is the code which I think should work for you:
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int opto = 12;
int buttonInput = 2;     // the number of the pushbutton pin
int buttonState = 0;         // variable for reading the pushbutton status

// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.m
pinMode(opto, OUTPUT);
pinMode(buttonInput, INPUT);
digitalWrite(buttonInput, HIGH);}

// the loop routine runs over and over again forever:
void loop()
{
  buttonState = digitalRead(buttonInput);
  if (buttonState == HIGH) {
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
  } else {

  }

}

Without much info about your camera, I'd imagine that the HIGH/LOW discrepancy is the issue. Another note: this code doesn't protect against bouncing. It's fine if as it is because the delays will cause the bounces to not be picked up. If you do a "blink without delay" type of sketch using millis() and a loop, you might need to fix this. Like I said, it'll work fine now, but it's kind a crude fix since it could cause problems later if mixed with other code.

Thanks for getting back to me. I think you're right with the LOW being the trigger here, it's a CANON 350D (Pretty old, it's all I had around that I could rag about) But it works like most canons, using a 2.5mm jack + 3 wires. GND, Focus and Trigger.

Would there be benefits for using blink without delay? My original intentions where to have it play the loop once when you push a button. Which made me wonder if it would be worth setting a separate void() with my camera behaviour in to clean the code. but might just be arbitrary

@Andrew Did you test the camera yet? From the wires you posted, it only makes sense to have it be pulled down to ground. If so, did it work right? As far as the blink without delay, I personally wouldn't implement it if you don't change any features. The only reason I could see implementing it is to have a "cancel" button. If you want the experience, go ahead, just remember to debounce the button. EDIT: I found a problem with your code that I didn't notice. I'm editing my answer right now.

source: Stack Exchange

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

sort: votes


text:
Arduino ATmega328P works but board (Uno R3) seems broken
This is the first time I'm using my Arduino. It's an Arduino UNO R3. I have two boards. One works, but the other doesn't. I changed the ATmega328P from the broken one to the good one and it works, so I can confirm that the controller works. The issue seems to be in the board.
When I plug the board it doesn't come up either in Mac or in Windows. The LED blinks and the output pins have voltage, but it seems that it's only getting electricity from the computer, it's like the data channels don't respond. The other board works perfectly both on Windows and Mac.
I checked the logs on the Mac and nothing changes when I plug the board. It's like I'm not plugging anything.
Is there a way to reset the board only? Maybe a component was badly soldered in the factory. I can't use the warranty because I got the board last year and never used it until now.

Might have something to do with the USB driver IC (I believe they're FTDIs?) if your computer is not recognizing the board. Unless you have a hot air rework station to replace the chip, you are probably just better off buying a new board.

Just to confirm - you are using the same cable with either board, right?

Try to reset the communication IC on your arduino uno. You can see the steps on this link  http://arduino.cc/en/Hacking/DFUProgramming8U2

The board doesn't even shows up in the device manager. I unplugged. @Nick I don't have the equipment to replace the chip. At least I have the ATMega chip that maybe I can use as a replacement in case the working board dies someday.

The R3 uses an ATmega16u2 in place of the FTDI. It is possible that it is not loaded, busted crystal, or it has no local power to it. It is a small SMT.
You could use your good Arduino setup as ICSP programmer to talk to the ICSP of the 16u2 to see it is alive. And if so then program it.

I can use the working board to program the chip of the broken one but I would like to know if there is a way I can test where the issue is and maybe fix the board. Without the board I can't easily use the ATMEGA for other purposes.

First setup your good working Arduino as a ISP programmer, to flash the boot loader to the suspect Arduino Board. once working, this proves your programmer. Then use avrdude to read the fuses of the suspect. If you get a response, other then 0x00 chip id. Then it likely can be programmed.

You should also check the voltages, to ensure it has proper powers. And if you got a Scope the XTAL pins to see if there is clock.

do you know where I can find instructions to do what you suggest? The board doesn't even shows up in the device manager. It only gets power, nothing else. The method you propose is an arduino to arduino or PC to arduino? because the PC to arduino is not an option.

I have a sketch, that runs on a Uno, that detects chip signatures on other boards. You can use that to verify if the other board is good.
http://www.gammon.com.au/forum/?id=11633
You just need six jumper cables, like this:

From your description it sounds more like the Atmega16U2 is not working, that is the USB interface chip, the small chip near the USB socket. You can use the same sketch and a similar interface to check that as well.

That should at least show that the chip(s) are alive and giving valid signatures.
You could use About this Mac -> System Information to see if the problem Uno is listed as some sort of USB device.

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


text:
How many interrupt pins can an Uno handle?
I am looking at using a 7 channel RC receiver with the Arduino Uno R3. In the documentation, there are mentions of a maximum of 2 interrupt pins, whereas on certain other blogs I have seen mentions of using upto 20 pins as interrupts, with PinChangeInt library. So, how many interrupts can the Arduino handle natively? And is this different from  how many can be handled with software support such as PinChangeInt?

There are two types of "pin change" type interrupts. The external interrupts, of which there are two on the Uno. They are called 0 and 1, however they refer to digital pins 2 and 3 on the board. These can be configured to detect rising, falling, change (rising or falling) or LOW.
In addition to that are "pin change" interrupts, which detect a change to the pin state in any of the 20 pins (A0 to A5, and D0 to D13). These pin change interrupts are also hardware based so, in themselves, will be as fast as the external interrupts.
Both types are slightly fiddly to use at the register level, but the standard IDE includes attachInterrupt(n) and detachInterrupt(n) which simplifies the interface to external interrupts. You can also use the Pin Change Library to simplify the pin change interrupts.
However, steering clear of the library for a minute, we can establish that pin change interrupts can be as fast, or faster, than external interrupts. For one thing, although pin change interrupts work on batches of pins, you don't have to enable the whole batch. For example, if you want to detect changes on pin D4, this will suffice:
Example sketch:
ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 if (PIND & bit (4))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D4)
  PCMSK2 |= bit (PCINT20);  // want pin 4
  PCIFR  |= bit (PCIF2);    // clear any outstanding interrupts
  PCICR  |= bit (PCIE2);    // enable pin change interrupts for D0 to D7
  pinMode (4, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

My testing indicates that it took 1.6 µs for the "test" pin (pin 5) to react to a change on the interrupt pin (pin 4).

Now if you take the simple (lazy?) approach and use attachInterrupt() you will find the results are slower, not faster.
Example code:
void myInterrupt ()
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of myInterrupt

void setup ()
  {
  attachInterrupt (0, myInterrupt, CHANGE);
  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

This takes 3.7 µs to change the test pin, a lot more than the 1.6 µs above. Why? Because the code the compiler has to generate for the "generic" interrupt handler has to save every conceivable register (push them) on entry to the ISR, and then restore them (pop them) before returning. Plus there is the overhead of another function call.

Now we can work around that by avoiding attachInterrupt() and doing it ourselves:
ISR (INT0_vect)
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of INT0_vect

void setup ()
  {
  // activate external interrupt 0

  EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
  EICRA |=  bit (ISC00);    // set wanted flags (any change interrupt)
  EIFR   =  bit (INTF0);    // clear flag for interrupt 0
  EIMSK |=  bit (INT0);     // enable it

  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

That is the fastest of them all at 1.52 µs - it looks like one clock cycle got saved somewhere.

There is one caveat though, for pin-change interrupts. They are batched, so if you want to have interrupts on lots of pins, you need to test inside the interrupt which one changed. You could do that by saving the previous pin status, and comparing it to the new pin status. This is not necessarily particularly slow, but the more pins you need to check, the slower it would be.
The batches are:

A0 to A5
D0 to D7
D8 to D13

If you just want a couple more interrupt pins, you could avoid any testing by just choosing to use pins from different batches (eg. D4 and D8).

More details at http://www.gammon.com.au/interrupts

There are two types of interrupts. What the Arduino Playground said:

The processor at the heart of any Arduino has two different kinds of interrupts: “external”, and “pin change”. There are only two external interrupt pins on the ATmega168/328 (ie, in the Arduino Uno/Nano/Duemilanove), INT0 and INT1, and they are mapped to Arduino pins 2 and 3. These interrupts can be set to trigger on RISING or FALLING signal edges, or on low level. The triggers are interpreted by hardware, and the interrupt is very fast. The Arduino Mega has a few more external interrupt pins available.
On the other hand the pin change interrupts can be enabled on many more pins. For ATmega168/328-based Arduinos, they can be enabled on any or all 20 of the Arduino's signal pins; on the ATmega-based Arduinos they can be enabled on 24 pins. They are triggered equally on RISING or FALLING signal edges, so it is up to the interrupt code to set the proper pins to receive interrupts, to determine what happened (which pin? ...did the signal rise, or fall?), and to handle it properly. Furthermore, the pin change interrupts are grouped into 3 “port”s on the MCU, so there are only 3 interrupt vectors (subroutines) for the entire body of pins. This makes the job of resolving the action on a single interrupt even more complicated.

Basically, the external interrupts are extremely fast since they're all hardware based. However, there is also the pin change interrupts, but those seem to be much slower because they are mostly software based.
tl;dr: the 20 interrupt pins together are much slower. The 2 interrupt pins are the fastest and most efficient.

EDIT: I just looked at the datasheet and it says that a pin change interrupt is triggered for any of the pins selected with no indication of which pin has changed (although it is split into three interrupt vectors).

For external interrupts, it'll tell you pin 3 just changed
For pin change it'll tell you a pin changed that you were
monitoring!

As you can see, a pin change interrupt adds a lot of overhead into the ISR that you have to handle by storing previous states and seeing if it's the pin you're worried about. It might be fine for a sleep state, but it's better to use the external interrupts.


text:
1 Wire temperature sensor
I bought a waterproof temperature sensor from Ebay, I am fairly new to this and not sure what I need or need to do in order to get the sensor to output the current temperature to the serial monitor.
Does anyone have any information on where I can get some information on how to wire this? I have looked at various videos online but they are all for a dallas temp sensor and use the dallas library.
http://www.ebay.co.uk/itm/181393039374?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1439.l2649

"The probe the temperature sensor DS18B20 original chip" from the product page. Look for the DS18b20 library.

This probe has the Dallas (now Maxim) DS18b20 sensor in it so you're already on the right track. Search for DS18b20 at arduino.cc. You'll find libraries and lots of forum discussions about using these sensors.
Also see page 6 of the DS18b20 datasheet; there are two schematics for wiring the device.
I'm using the parasitic mode (Figure 4 on that page) except I eliminated the transistor switch and connected the MCU pin for the strong-pullup directly to the one-wire bus.


text:
Does the square-wave nature of PWM dictate how much resistance you need?
I think the answer is yes, but I wanted to ask the question anyway for future common reference. And to check my understanding.
Say I want to power 10 LEDs with PWM with my Mega 2560. I have a bunch of 200 ohm resistors.
I know the Mega and most other Arduinos can safely provide a maximum of 200mA total current. 200mA / 10 is 20mA per LED maximum.
Using my 200 ohm resistors I can calculate how much voltage will supply 20 mA of current:
V = 200 ohms * 20mA
V = 4V

So I just need to make sure to analogWrite less than or equal to 4V to each of the ten LEDs and I won't cross the 200mA threshold. That's if PWM was true analog.
However, PWM is not true analog, and if I analogWrite 4V to each pin, they're going to spend most of the time at 5V and some of the time at 0V.
When every pin is at 5V the board has to supply
(5V / 200 ohms) * 10 = 250mA

Which is over the spec, so I am in danger of damaging my board. Right?
So if I want to calculate the maximum current draw of the 10 LEDS being powered simultaneously with PWM, I have to assume that they are all getting 5V regardless of what I analogWrite to them. I do not actually have control over the voltage, I only have control over the resistance.
Thus in order to be safe I need to get some new resistors with resistance:
5V / 20mA = 250 ohms

Is this all correct?

Just to check, are you intending to connect all 10 LEDs directly to a single PWM pin? That would be a very bad idea. At best, it simply won't work. At worst, you'll fry something. (Each individual pin is only capable of sourcing a small amount of current.)

Nope, separate pins on a Mega, thanks though.

The Mega can support 800mA total current, spread across the ports per the notes listed under Table 30 or 31 (I don't have a data sheet handy). VCC and GND pins can support 200mA each, there are 4 of each.

It's... mostly wrong. For three independent reasons.
The LEDs themselves, like all diodes, absorb some of the electrovoltaic potential of the electricity passing through them, resulting in a voltage decrease in their circuit. This means that although 5V is being used to power the resistor and LED in a circuit, only some of that voltage is passing through the resistor. If we use a typical (for blue, white, and other exotic colors) forward voltage (Vf) of 2.8V, this means that the resistor only has 2.2V across it. For a 200ohm resistor, this means that only 11mA is passing through the circuit. If you want 20mA to pass through the LED you need to use a resistance of 110ohm instead.
Second, the voltage from the MCU pins themselves depend on the current passing through them. Section 32.7 of the ATmega2560 datasheet, "Typical Characteristics - Pin Driver Strength" has charts for voltage versus current for both sourcing and sinking current; at 20mA the voltage drops to about 4.5V, which means that the resistance required for a 2.8V LED drops from 110ohm down to 85ohm.
Third, although semiconductors (i.e. the MCU and LED) can be damaged when too much current passes through them, it is not the current itself that causes the damage. The current passing through the voltage drop results in a consumption of power, and this power subsequently turns into heat. This heat then causes the breakdown of the semiconductor material. Even a junky, third-hand LED can take bursts of current up to 35mA or so without being damaged, provided the duration is limited. With a PWM signal this duration is directly linked to both the frequency and the duty cycle of the signal. You will need to see the datasheet for the LED in question to figure out what the maximum safe current and duration are, but the implication is that if you keep the frequency high enough and the duty cycle low enough, you can get away without any resistor at all and both the MCU and LED will survive.

This goes deeper than I thought xD So the actual current being pulled from the Arduino is ((5V - forward voltage) / resistance)?

It will be close to that. See the second point.

Note that PWM does not actually drop the output voltage. It generates variable length pulses of 5V at different "duty cycles" (percent on vs percent off).
For an LED you might get away with using PWM to vary the power that passes through the LED since it can probably tolerate over-current for brief intervals.
What you should really do is calculate resistor value based on LED voltage drop and maximum current:
Say you have a red LED with a 1.8V voltage drop.
5V supply - 1.8 LED voltage drop = 3.2 V
If the LED can handle a max of 15 mA, that would be
3.2/.015 ≈ 213Ω. Round up to the nearest 10% resistor value, 220Ω. That would give you about 14.8mA through the LED, slightly less than it's max.
If you then power the LED through a PWM pin, running the analog output at max will drive the LED at max brightness, and lower analog output levels will make the LED appear dimmer. Note that the LED will actually be rapidly flashing between full intensity (limited by your current limiting resistor, assuming you have one) and off. Our eyes average out that flashing light and see it as being a dimmer, constant light.

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


text:
Non-blocking strobing code?
I'm trying to figure out how to create some non-blocking code to strobe some RGB leds with analogwrite  7 times a second; I'm really not to sure how to go about this. If anybody could give me some help that'd be great! :)

Which part of the code did you want to unblock?

By non-blocking I mean not using the delay function. And the question is stated above, perhaps you don't understand?

analogWrite() doesn't call delay().

Look at the BlinkWithoutDelay example

Blink with out delay uses boolean which just turns it on or off if I understand correctly. I need to change the current state which could be 0-255 to the specified new one, and back. I'm not sure how I would use boolean variables then.

@ignacio. So heres the deal: I'm using the analogwrite pwn to control an RGB LED. But I want it to STROBE  (on then off) at a specific Hertz. So say normally to do thay you would call analogwrite X then delay for specified period then analogwritelow; so on so forth etc... I can't use delay as it will.block other code. So I need to do it using timers. How would I go about it using timers?

With either an overflow ISR or CTC and a compare ISR.

Care to explain that more?

See the timer section of the MCU datasheet, the interrupt section of the Arduino reference, and the interrupt section of the AVR LibC documentation for more details.

What you want can be achieved with your MCUs timers and their associated interrupts. Timers are basically counters that run inside your hardware and they run decoupled from your code. Since one usually knows how fast these timers tick (e.g. how long it takes to count from one to two and so on) you can specify events that happen when a certain amount of timer ticks passed.
I suggest you have a look at SimpleTimer and Timer1 (the second page is only for ATmega168/328)
Both pages include some code samples where they specify some method that will be called every x milliseconds.

SimpleTimer isn't a hardware timer solution. In fact, it won't work if you have blocking code...

Timers are the best way to go, (much) less overhead and you don't have to worry about it elsewhere in your code (other than managing variable use between your main loop and your ISRs).
But I do have a habit of doing things the hard way in code first and then move to timers once I've got it the way I'd like.
Here is sample code to flash the on board LED X times per second, I have calculated it to mean, ON 7 times per second and OFF 7 times as well (meaning, there is a change of state 14 times per second).
This code isn't efficient, it doesn't take into consideration that the value is already set or not, it just writes the value that it should be right now.
Finally, to go to analogWrite and use PWM, just change:
digitalWrite(LED, HIGH);

to
analogWrite(NEW_PIN, PWM_VALUE);

code:
#define LED               13
#define TIMES_PER_SECOND  7

const int M1 = 1000 / TIMES_PER_SECOND;
const int M2 = 1000 / TIMES_PER_SECOND / 2;

void setup(){
  pinMode(LED,OUTPUT);
}

void loop(){
  if(millis()%M1<M2){
    digitalWrite(LED, HIGH);
  } else {
    digitalWrite(LED, LOW);
  }
}

Remember there is overhead with digital (and analog) writes, so (as I mentioned) you could check to see if the value is set already or not and skip the write.


text:
Arduino ADC Reference Voltage if it is Battery Powered
I am looking to possibly monitor battery power to the Arduino using its ADC.  This is fairly straight forward and simple (especially if using the Arduino API); however, if the battery is powering the Arduino and is unregulated externally, won't the ADC reference voltage constantly be dropping with the battery?  In other words, wouldn't the ADC value would constantly read the same value (the max value) even though the battery would actually be decreasing in voltage?
If this is the case, it would be both inefficient and pointless to measure the battery voltage.

... won't the ADC reference voltage constantly be dropping with the battery?

Yes, which is why you either use or measure an internal bandgap reference instead.
Use the analogReference() function to select a reference appropriate for the board in use. Note that you will need to use a voltage divider to reduce the battery voltage to a value below that of the selected reference if you wish to measure it.
To measure the bandgap voltage instead (using AVCC as a reference and working "backwards") you will need to set MUX[3:0] in ADMUX to 0b1110 and then perform an ADC reading directly (set ADSC in ADCSRA and wait until it resets, then read from ADC[H:L]).
As always, see the MCU datasheet for details.

Great information, now I think I can proceed on my own.  I was hoping there was some sort of internal reference that could be used.  As you suggested, I will need to voltage divide the power voltage down below AVccref, however, I am looking to maximize battery life in all possible aspects so I was going to use a large equivalent resistance for the divider to ensure I have less than a uA of leaking current.  Do you see any issues with this?

The ADC impedance is only 100Mohm. Consider measuring the internal reference instead.

FYI I found this awesome blog after the answer @Ignacio posted:  link

@ryeager's link to http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/#comment-71836 has this code for reading the Arduino's battery voltage:
long readVcc() {
  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
    ADMUX = _BV(MUX5) | _BV(MUX0);
  #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
    ADMUX = _BV(MUX3) | _BV(MUX2);
  #else
    ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  #endif

  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
  uint8_t high = ADCH; // unlocks both

  long result = (high<<8) | low;

  result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
  return result; // Vcc in millivolts
}

The trick here is that it measures its internal reference of 1.1V using the battery voltage, and then inverts it to calculate the unknown reference voltage.
The ADMUX magic in this code can enable other interesting ADC readings, such as differential measurements, and differential ADC measurements with gain, depending on the component and datasheet.


text:
Executing multiple functions/commands on Arduino
I am using an RFduino and an iOS application to control some RGB LEDs.
This is how I'm sending a string command to the module:
- (IBAction)fadeButtonPressed:(id)sender {
    [rfduino send:[@"fade" dataUsingEncoding:NSUTF8StringEncoding]];
}

These command(s) are coming back just fine on the RFduino side:
void RFduinoBLE_onReceive(char *data, int len) {
  if (strncmp(data, "fade", 4) == 0) {
    // begin fading chosen LED colour
  }
}

Is there a better way of executing multiple functions on Arduino? It seems to me that there should be a better way of doing what I'm trying to do.
Originally for example I was getting an issue where the "fade" string was coming back as "fadek" so I used strncmp(data, "fade", 4) instead of strcmp(data, "fade") and this fixed the issue.
I guess I'd like a way of cleaning up my code and perhaps make it easier to introduce new bits of functionality depending on which strings are coming back.
The functions I would like to be able to do would be controlling of the RGB colours and then Fading or Blinking that particular chosen colour.
What if I wanted to introduce faster blinking? Rather than setting another command integer and adding another condition is there a cleaner approach?
The selection of the colours is set by selection of a color wheel within my iOS application. This is working fine. The problem is that the Blinking and Fading does not blink/fade the selected colour (command 0).
Here is my entire sketch so far:
#include <RFduinoBLE.h>

// Pin 2 on the RGB LED.
int rgb2_pin = 2; // red
int rgb3_pin = 3; // green
int rgb4_pin = 4; // blue
int brightness = 0;
int fadeAmount = 5;

// Command properties.
int command = 0;

void setup() {
  // debug output at 9600 baud
  Serial.begin(9600);

  // Setup the LEDs for output.
  pinMode(rgb2_pin, OUTPUT);
  pinMode(rgb3_pin, OUTPUT);
  pinMode(rgb4_pin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop() {
  if (command == 1) { // Fade in/out chosen colour.
    analogWrite(rgb2_pin, brightness);
    analogWrite(rgb3_pin, brightness);
    analogWrite(rgb4_pin, brightness);

    // Change the brightness for next time through the loop:
    brightness = brightness + fadeAmount;

    // Reverse the direction of the fading at the ends of the fade:
    if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
    }

    // Wait for 30 milliseconds to see the dimming effect
    delay(30);
  } else if (command == 2) { // Blink
    digitalWrite(rgb2_pin, HIGH);
    digitalWrite(rgb3_pin, HIGH);
    digitalWrite(rgb4_pin, HIGH);
    delay(200);
    digitalWrite(rgb2_pin, LOW);
    digitalWrite(rgb3_pin, LOW);
    digitalWrite(rgb4_pin, LOW);
    delay(200);
  }
}

void RFduinoBLE_onConnect() {}

void RFduinoBLE_onDisconnect() {}

void RFduinoBLE_onReceive(char *data, int len) {
  Serial.println(data);

  // Each transmission should contain an RGB triple.
  if (strncmp(data, "fade", 4) == 0) {
    command = 1;
  } else if (strncmp(data, "blink", 5) == 0) {
    command = 2;
  } else { // Change colour.
    // Reset other functions.
    command = 0;

    if (len >= 3) {
      // Get the RGB values.
      uint8_t red = data[0];
      uint8_t green = data[1];
      uint8_t blue = data[2];

      // Set PWM for each LED.
      analogWrite(rgb2_pin, red);
      analogWrite(rgb3_pin, green);
      analogWrite(rgb4_pin, blue);
    }
  }

  Serial.println(command);
}

+1 for the way you've posted your question. I hate it when people don't write comments in their script. But you did write comments!

Ended up going with something like this:
#include <RFduinoBLE.h>

// State properties.
int state = 1;
char command;
String hexstring;

// RGB pins.
int redPin = 2;
int grnPin = 3;
int bluPin = 4;

// Setup function to set RGB pins to OUTPUT pins.
void setup () {
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.deviceName = "iOS";
  RFduinoBLE.advertisementInterval = MILLISECONDS(300);
  RFduinoBLE.txPowerLevel = -20;
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop () {
  switch (command) {
    case 1:
      // Blink.
    break;
    case 2:
      // Fade.
    break;
  }

  //RFduino_ULPDelay(INFINITE);
}

// Converts HEX as a String to actual HEX values.
// This is needed to properly convert the ASCII value to the hex
// value of each character.
byte getVal (char c) {
  if (c >= '0' && c <= '9') return (byte)(c - '0');
  else return (byte)(c - 'a' + 10);
}

// Process each function/command.
void processCommand (int command, String hex) {
  switch (command) {
    case 'b':
      command = 1; // Set blink mode.
    break;
    case 'f':
      command = 2; // Set fade mode.
    break;
    case 'c':
      // We put together 2 characters as is
      // done with HEX notation and set the color.
      byte red = getVal(hex.charAt(1)) + (getVal(hex.charAt(0)) << 4);
      byte green = getVal(hex.charAt(3)) + (getVal(hex.charAt(2)) << 4);
      byte blue = getVal(hex.charAt(5)) + (getVal(hex.charAt(4)) << 4);

      // Set the color.
      setColor (red, green, blue);
    break;
  }
}

// Sets the color of each RGB pin.
void setColor (byte red, byte green, byte blue) {
  analogWrite(redPin, red);
  analogWrite(grnPin, green);
  analogWrite(bluPin, blue);
  delay(200);
}

// This function returns data from the radio.
void RFduinoBLE_onReceive (char *data, int len) {
  for (int i = 0; i < len; i++) {
    stateMachine(data[i]);
  }
}

// Main state machine function, which processes
// data depending on the bytes received.
void stateMachine (char data) {
  switch (state) {
    case 1:
      if (data == 1) {
        state = 2;
      }
    break;
    case 2:
      if (data == 'b' || data == 'f' || data == 'c') {
        command = data;
        hexstring = "";
        state = 3;
      } else if (data != 1) { // Stay in state 2 if we received another 0x01.
        state = 1;
      }
    break;
    case 3:
      if ((data >= 'a' && data <= 'z') || (data >= '0' && data <= '9')) {
        hexstring = hexstring + data;
        if (hexstring.length() == 6) {
          state = 4;
        }
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
    case 4:
      if (data == 3) {
        processCommand(command, hexstring);
        state = 1;
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
  }
}

Does the delay(), millis() etc. work on the RFduino?

@Phataas: Not sure, why?

I saw you removed them.

@Phataas: Oh, I just noticed that. I'll add them back in after the analogWrite() calls.


text:
Best way to interact arduino and python
So, i've worked with the pySerial module for python, where I communicated with my arduino via serial. However, this module only works for 32bits and I would like to make my project work on both architectures (I know the person could just install the 32-bits version on the 64-bits architecture). Also, the connection fails a lot of times and I wasn't able to correct it.
I think I can use the true USB power of the arduino Leonardo to connect to the python in a different way, but I don't know where to start. But I think this approach will be more professional.
Im really intersted in learning, so if you guys could at least indicate documents so I can understand how to make this connection between Leonardo and Python, I'll be happy. I've read the arduino page about the CDC but couldn't find useful information.
Thank you so much.
Update:
When i used serial, I had problems with messages getting acumulated at the buffer, and then after some seconds i was reading 10s delayed messages. Also, when I sent a string like: "12345678", it was really easy to get one number less, like: "1345678". This happened frequently to me. So I think I need to implement a protocol to deal with these problems.

Where do you get the idea that PySerial is not x64 compatible? It most certainly is. Also, I've done enormous amounts of data-transfer over serial interfaces. They can be extremely reliable. If you are having issues, it's not because it's a serial connection, there are deeper issues.

I concur with @Connor Wolf, serial comms are perfectly reliable.  You may need to implement some buffering and/or handshaking in your protocol.

I did some work in Java using USB some years ago and I can share some experiences:

Things are not neary as straightforward as using serial.
Your code will probably be platform specific, windows being a bit more weird about handling usb. (unless using something to abstract that away, like PyUSB which wraps libUSB or openUSB, this however does not guarantee platform independency because these libraries also have their weirdnesses).
If you drop down to USB level programming, things can get very messy (again, this can be abstracted away). USB is (at least in my opinion) a complicated protocol, especially for beginners.

So unless you really need something that only USB can provide, a nice and dandy serial communication will give you much less headaches. Thats why serial did not die until now.
As for debugging why your communication is not reliable I would try several things:

See if your application might send something that is interpreted as a control character
Drop your baud rate to something lower and see if it still loses data. If so, you might overflow the buffer of your receiver (and you would need flow control in this case)
Check your hardware! I've had bad wires or solders on numerous occasions

I'll use Serial, then. Do you have some ideas of what protocol I should implement? Because the pure serial comunication fails a lot.

If you update your question to show how it "fails a lot", we might be able to point out how to make it better.

I added some suggestions.


text:
Is volatile needed when variable is accessed from > 1 ISRs, but not shared outside ISRs?
It's clearly documented that when global data is shared with an ISR and the main program, the data needs to be declared volatile in order to guarantee memory visibility (and that only suffices for 1-byte data; anything bigger needs special arrangements to guarantee also atomicity). Here we have good rules:

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

But is volatile needed when the variable is accessed from > 1 ISRs, but not shared outside ISRs? For example, I have a function that maintains internal state using a static variable:
void func() {
    static volatile long counter; // volatile or not?
    // Do stuff with counter etc.
}

That function is called in two ways: from pin interrupt, and from TimerOne library:

attachInterrupt(0, func, CHANGE);
Timer1.attachInterrupt(func);

There are no atomicity problems, since when an ISR is entered, interrupts are automatically disabled, but this volatile is more of a compiler question: what is cached and what is not.
Better safe than sorry, of course...

volatile only informs the compiler's code generator that the variable may be modified by something other than the code being generated, so not to assume any copy of it remains accurate.
ISR code must be written/generated under the assumption that it has no context at entry, and preserve the CPU's context around its (ISR's) own operation. So, as with the indivisbility of non-atomic operations, volatility depends, in this case*, on whether or not interrupts are allowed to nest. If non-nesting is guaranteed, the shared variable can not change by other than this ISR during its own execution. If your ISR might someday be used in an environment where interrupts are allowed to nest, then that constraint will no longer hold.
* in this case:
I'm assuming a software-maintained variable here. If we're talking about a variable that can be updated by a hardware event, a timer register for example, all bets are off: the variable is volatile no matter what.

So, as long as I don't change Arduino's default "interrupts don't nest" behavior, then the variable doesn't need to be volatile, since it's not modified by anything other than the code being generated; compiler can "assume" that the ISR executes linearly, and it does, as long as interrupts don't nest. That makes sense. Thanks!


text:
Are function pointer assignments atomic in Arduino?
The following snippets are from TimerOne library source code:
// TimerOne.h:
void (*isrCallback)();

// TimerOne.cpp:
ISR(TIMER1_OVF_vect) // interrupt service routine that wraps a user defined function supplied by attachInterrupt
{
  Timer1.isrCallback();
}

// TimerOne.cpp:
void TimerOne::attachInterrupt(void (*isr)(), long microseconds)
{
  if(microseconds > 0) setPeriod(microseconds);
  isrCallback = isr; // register the user's callback with the real ISR
  TIMSK1 = _BV(TOIE1); // sets the timer overflow interrupt enable bit
  resume();
}

The question: if the timer is already running, and the main program calls attachInterrupt(), could the timer interrupt occur there during the function pointer assignment isrCallback = isr;? Then, with lucky timing, Timer1.isrCallback(); function pointer would consist partly of the old and partly of the new address, causing the ISR jump to a bogus location?
I suppose this might be the case, since function pointers are certainly wider than 1 byte, and accessing > 1 byte data isn't atomic. Possible workarounds could be:

Always call detachInterrupt() to make sure the timer isn't running, before calling attachInterrupt(), i.e. clarify Timer1 docs.
Or, modify Timer1, disabling timer overflow interrupts temporarily just before isrCallback = isr;

Does this make sense, or is there something in Timer1 sources or function pointer assignments that I've missed?

Have a look at the code for attachInterrupt() and detachInterrupt() in
/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino/WInterrupts.c (well, that's where they are on a Mac, anyway. Arduino file structure on other OSes' probably looks similar in the lower levels of the path).
It appears that attachInterrupt() assumes that the interrupt in question is not yet enabled because it writes the function pointer without taking any precautions. Note that detachInterrupts() disables the target interrupt before writing a NULL-pointer to its vector. So I'd at least use a detachInterrupt() / attachInterrupt() pair
I'd want to run any such code in a critical section, myself. It appears your first way (detach, then attach) would work, though I can't be sure it couldn't miss an unfortunately timed interrupt. The datasheet for your MCU might have more to say on that. But neither am I sure at this point, that a global cli()/sei() wouldn't miss it either. The ATMega2560 datasheet, section 6.8, does say "When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example", seeming to imply that it can buffer an interrupt while the interrupts are off.

It's indeed useful to dive to the sources:) TimerOne's attach / detach interrupt mechanism seems to be done similarly as the standard (WInterrupt's) and so has the same "features".

It looks like you have a point. The logical thing to do would be to disable interrupts in such a way that you don't re-enable them if they were disabled in the first place. For example:
  uint8_t oldSREG = SREG;  // remember if interrupts are on
  cli();                   // make the next line interruptible
  isrCallback = isr;       // register the user's callback with the real ISR
  SREG = oldSREG;          // turn interrupts back on, if they were on before

"When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example"

The intention of this is to let you write code like this:
  sei ();         // enable interrupts
  sleep_cpu ();   // sleep

Without that provision you might get an interrupt between those two lines, and thus sleep indefinitely (because the interrupt which was going to wake you has occurred before you slept). The provision in the processor that the next instruction, after interrupts become enabled if they were not enabled before, is always executed, guards against this.

Wouldn't it be more efficient to TIMSK1=0; TIFR1=_BV(TOV1); isrCallback=isr; TIMSK1=_BV(TOIE1);? It spares one CPU register and doesn't contribute interrupt latency.

What about the other bits, like ICIE1, OCIE1B, OCIE1A? I understand about the latency, but interrupts should be able to cope with a couple of clock cycles of not being available. There may be a race condition. The interrupt might be triggered already (ie. the flag in the CPU is set) and turning TIMSK1 off might not stop it being handled. You might also need to reset TOV1 (by writing 1 to it in TIFR1) to ensure that doesn't happen. The uncertainty there leads me to think that turning interrupts off globally is the safer course.


text:
Do I need to use a resistor if I am using a potentiometer to control an LED's brightness?
I am currently tinkering with an arduino, and am using a potentiometer to change the brightness of an LED.
I understand that usually, a resistor is added to the circuit to limit the current flowing through the circuit in order to prevent the LED from burning out.
However, as I am currently using a potentiometer to adjust the LED's brightness, AND as a potentiometer is basically a variable resistor, would I still need a resistor to prevent the LED from burning out? Currently, I do not see a difference between using a 220 ohm resistor and not using it, as the LED seems unaffected.
My code:
const int pot=A0;
const int led=11;
int potValue;

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

void loop(){
  potValue = analogRead(pot);
  potValue=map(potValue,0,1023,0,255);
  analogWrite(led,potValue);
  Serial.println(potValue);
}

PS: My LED is hooked up to the arduino's PWM pin, and connected to ground on a breadboard.

Without a good quality picture of your setup or some schematics, it's hard to tell what's going on, but from your description, what you're doing is potentially harmful for the LED and the output pin D11.
Yes, LEDs almost always need series resistors to limit their current. They don't limit currents and will burn if you don't do it for them.
If you had the pot in series with the LED, which seems to be what you think is going on, you'd still need a series resistance so that when the pot is all the way to one side, effectively behaving like a 0Ω resistor or a short, you'd still be limiting the current with the 2nd resistor. One would usually use Ohm's Law to calculate that 2nd resistance so that it lets the maximum current the LED can take when the pot is at 0Ω position, usually 20mA for common LEDs.
But that's not how your circuit seems to be wired. The pot is indirectly controlling the LED through an analog input and a PWM output via MCU. So it's not limiting the LED current, in the traditional sense. The pot seems to be wired between 5V and GND with the middle lead (the cursor) hooked up to the analog input A0. That's a variable voltage divider configuration that let's you select a continuous voltage between 0 and 5V that is in turn converted to a value between 0 and 1023 by the MCU ADC (Analog to Digital Converter) - that's the result of the analogRead() call.
That value is then fed to a PWM analog output, through the analogWrite() call, that will output a square wave to the LED. The relative position of the pot will determine the duty cycle of the PWM, i.e., how long the square wave is HIGH or LOW. The problem here is that this circuit where the LED is wired should have its own series current limiting resistance.
To me, if you didn't burn the LED or the D11 pin yet, is pure luck. If you were to turn the pot all the way to maximum brightness (don't do it), the PWM output would act like a digital output put in HIGH level (5V continuously), and without a current limiting resistor, the D11 pin would exceed it's 40mA absolute maximum source current and burn. Unless there's another factor limiting the current that I don't know of, that is.
There are some exceptional cases in which you can control the LED voltage closely so you don't need to limit the current (multiplexing, constant-current supply etc.), but these are really advanced configurations for us newbies. So, from know on, do it like I do it: ALWAYS put a series resistor, until you become familiar with these advanced configurations.
Finally, below are some links that you may find helpful about the topic:

SparkFun Tutorial on LED Current Limiting Resistors
WikiPedia Article about LED series resistors

Thank you for the prompt and detailed reply, you were right in assuming that the pot is controlling the LED through an analog input, and an output via a PWM.I've turned the pot to max brightness momentarily(never more than 1 sec), and am sure glad i've never left it there for extended periods of time!


text:
Connect two Arduinos using I²C (wiring)
Altough having found a lot of documentation concerning wiring of I²C buses, I'm still not sure about the following question:
If both devices use separate power sources, is it a good idea to connect VCC/GND of those two devices?
I have two lines for SCL and SDA, connected to SCL/SDA pins on both devices A and B. The master device's VCC is connected to both lines using a pull-up resistor. Now as far as I understood, VCC/GND of the two devices should not be disconnected but I'm afraid I'd damage something if I'd connect them. As two separate power sources will never provide exactly the same voltage that would result in high currents, won't it? Or should I just connect them using some resistor to avoid high currents but provide the same voltage level?

The VCC lines aren't directly connected - you just have a shared data line with some voltage on it, which is always lower than VCC because of the resistor. Each device "talks" to the I2C bus by briefly connecting those lines to GND, which is common between both devices. Current is limited by the pull-up resistor, so it never gets too high. This makes it safe to directly link devices running at slightly different voltages.

Ok, only connecting GND sounds better to me. Tried it but it did not work yet (as in I don't receive anything). Potential difference at the pull-up resistor (1k) is only 2V - I'm wondering where the remaining 3V would go? I would have expected that there's no notable resistance on the pins in TWI-mode? Might that be a problem?

I2C switches the pins between GND and "high Z" which resembles being disconnected. They only affect the shared data lines when they want to send a "0" by grounding the line, otherwise they just let the pull-ups do their job.

Note: One device needs to be in I2C slave mode. You may find it simpler to switch to serial communications instead.

@sburlappp Some devices require I2C.

True, but he was linking two Arduinos. He may have more flexibility.

Some sensors will follow, I2C is out of question.

Too late to edit: Some sensors will follow, I2C is out of question. What you mentioned concerning "high Z" - that's exactly what I've been wondering about: if that resembles being disconnected, why is the measured potential difference at the pull-up resistor 2V? "Only 2V" in my previous comment was bad expressed: I mean - it should be 0V as "high-Z" does not drain? So while I'm not sending voltage should be 5V on any side of the pull-up?

When you connect your meter to check the voltage at the resistor, you're closing the circuit through the meter (which contains a high-ohm resistor). Otherwise the voltage wouldn't have a path to GND and nothing would flow.

I'm checking the voltage at both resistor pins, so I'm not closing the circuit. Seems like there has been some misconfiguration on the master's side and the pin has not been in high-Z state. Now it is and the potential difference at the pull-up resistor is 0V (what I would have expected so far as in I2C idle state there is no current), thus no potential difference on the pull-up resistor.

Here's what you need to do:

Leave the VINs disconnected. I'm not sure that it's a bad idea, but it is pretty much pointless. Like sburlappp said, the resistors lower the voltage between them (and reduce the current). With a resistor, it wouldn't hurt it, but there's really no need.
Connect the grounds directly. Here's the problem: voltage is relative; it is measured very much like gravitational potential energy. It's the difference between the amount of electricity in both parts that determines the voltage. I'm pretty sure that if you don't, with the extra power, it could fry a component. That would happen when there is a lower concentration of electrons in "ground" on one of the boards than the other. That could result in many volts being passed along to the board. I haven't had this happen to me, nor have I really heard about this happening, but I guess it is a possibility.

I'm not sure if I understood you correctly, but are you suggesting connecting grounds but also mentioning that that could fry a component? Or do you mean something different by connecting grounds, e.g. using one common power source?

@user1034081 I saying that if you don't connect the grounds there might be a possibility of something getting fried. Also, with the different voltage levels, the signals often act weird, thus it won't work if they aren't connected. There's no risk with connecting the grounds.


text:
Asynchronous function calls in Arduino sketch
In an Arduino sketch, is there a way to make asynchronous function calls within the loop? Like listening to requests through http server and process them in a non-blocking way.

If you're not a C++ beginner, then you could take a look at Cosa library (https://github.com/mikaelpatel/Cosa). It is a complete rewrite of Arduino library to make it better: OOP and generally interrupt-driven. I think they support HTTP, but I haven't checked that part yet.

Yes and no. You're kinda vague on what you want to do. I've made this into a few different sections (mainly focused on reading sensor data... it applies to everything but that's the context I'm using):
Threads
AFAIK all Arduinos only have one core (they can do one thing at once). For most Arduino boards, hardware multithreading isn't supported. However, there are ways to implement software multithreading. The approach by AsheeshR wouldn't work well for functions that take a long time to complete (i.e. something in a library that takes a while, or a delay) because it would get jammed up by those instructions, but it would work well for short functions like pinMode(). The Protothreads library listed there might be better at this, but I don't really know.
It'd be hard to orchestrate this with HTTP, especially since you have to make
Delays
A common way for a sketch to stall is the use of a delay. This can be solved by using, in the main loop, a if statement and the millis() function that returns a time (not a clock time, but rather the time since the Arduino started). You could also do a loop within the loop to poll sensor data.
The millis() approach wouldn't work well with things that cause the whole program to stall (i.e. more delays or loops that last a noticeable amount of time). Note that 100ms IIRC is the general maximum time to make a UI not seem laggy.
Interrupts
Interrupts are a great way to keep things almost asynchronous. They run a short piece of code (that you specify) every time a pin state changes. It breaks from the loop(), and goes back where it left off once the "ISR" has been ran. I don't have much time to explain how to do this, but a quick Google search will yield a lot of results.

As far as you example, the threading section would be the most applicable. This topic is pretty vague, so you'll have to experiment with a few things and find something that works.

I just posted some code for a task scheduler on the playground the other day, you may want to take a peek, maybe you can adapt it to your needs.
The Arduino's processor is inherently single-threaded and cannot multi-task. As has been mentioned there are however ways to create the illusion of multi-tasking. Annonomus Penguin hit on those pretty well.
Also check out TimerOne (It's probably better ;)

TimerOne is a bad idea because it works with avr-based arduinos only. For example my Wemos D1 R1 doesn't work

You can definitely make asynchronous code on devices with only one thread. This is what the "static" keyword is for in C. It helps you to setup functions as a "state machine" so that they can run concurrently with other functions.
Let's take a simple function for example. These are just made up functions and not meant to be compiled in any IDE, just to show you the general principles.
char read_bit_sync()
{
    while ( digitalRead(PIN_CLOCK) ) {}
    while ( !digitalRead(PIN_CLOCK) ) {}
    return digitalRead(PIN_DATA);
}

void loop()
{
    char c = read_bit_sync();
    Serial.println(c);
}

In the example code above, we wait for the clock pin to go high and then low again, and then on the falling edge we read the bit and print it to the Serial output in a loop.
The problem is, what if we want to read this pin asynchronously? These "while" loops cause the whole program to freeze until it receives a bit.
The trick is to reimagine our algorithm as one that can be done in many small steps that each can be completed in a very short amount of time, so that the function will need to be called repeatedly until those steps are completed.
int read_bit_async()
{
    static int state = 0;
    int ret;

    switch (state)
    {
        case 0:
            if ( digitalRead(PIN_CLOCK) )
            {
                return -1;
            }
            state++;
            return -1;
        case 1:
            if ( !digitalRead(PIN_CLOCK) )
            {
                return -1;
            }
            state++;
            return -1;
        default:
            ret = digitalRead(PIN_DATA);
            state = 0;
            return ret;
    }
}

void loop()
{
    int c = read_bit_async();
    if (c != -1)
    {
        Serial.println(c);
    }
}

In the example above, the function starts in a "0" state which it will remain in that state until it reads that the clock pin is high. It then transitions into a "1" state which it then will remain in until the clock pin is low. It then transitions to a "2" state which the next time you read it, it will return the bit read, and then reset its internal state to the "0" state.
Now in the main loop, we can call the read_bit_async() every iteration of the loop and it will return -1 when it's still "awaiting" the bit but when it received the bit then we get the actual bit value. The main loop can continue to run and process other code while waiting for the bit to be received.
I've used in this past to, for example, write a library that can read keyboard input from a PS/2 keyboard asynchronously alongside the main program. I've also used it to write a communication protocol that could send bytes of data down a single wire asynchronously, so if you have two wires for upstream and downstream data then the two devices could communicate without blocking the main program loop.
For what you are personally trying to do, let's say you receive an HTTP request and you want to respond to it with an HTTP file, but sending out the whole file is too time consuming. You could have each iteration send out only one byte.
You could also have a "listening", "processing", and "responding" state where at first it is listening for a request, and then if it receives one it switches to the "processing" state where it interprets the request, and then after that it switches to the "responding" state where it produces the output.
Also, the second block of code I wrote is not necessarily the most optimal, for example the last two states can be merged into one, but I prefer to write them this way because I find it to be more clear and easier to follow along with.
If you want to create a non-blocking asynchronous function on a single thread, the easiest way to do it is to reimagine the algorithm you're trying to write as a state machine that can be broken up into many many different tiny parts, where enough iterations of these parts can eventually complete task, and then to implement this.
When I say "tiny" I mean mostly in terms of speed. If a single iteration of the function takes too long, it can noticeably interfere with other asynchronous functions, so you want to make sure each iteration can be done in very little time. If a single iteration takes too long, then you should try to figure out how to break it up into even more states.


text:
Can I use arduino and mobile phone screen to make a touch board?
I'm new to Arduino, I want to use Arduino and a mobile phone screen to make a simple touch board.
This phone screen I mean, is like this:

Can I connect it to Arduino, and when my fingers touch the screen, Arduino can get the events?

From what I can tell, Nintendo DS screens are easy to inference (they even have breakout boards) and very cheap, but they are resistive, thus they need pressure to use. They aren't the kind on a iPhone, and are only one touch point.

Without details we can't answer the question.  You will need technical specs and/or a datasheet for the screen.

First, find a suitable phone screen! Good luck. Most of the touch screens that I have found are resistive, and will never feel like an iPhone. Try googling "Arduino touch screen". Adafruit have a promising one.
Once you find your screen, you will need to interface to it. With luck it will come with a pre-built library. Otherwise you will be up for quite a lot of coding.


text:
Zigbee Relay board communication with Arduino
I have bought this wireless ZigBee relay board.
I was wandering about an arduino sketch to get started, I have searched for 2 days now but with no results.
What I was thinking of is to have an Arduino with ZigBee module to send signal to another ZigBee device on top of the relay, to be able to open/close relay.
So, can anyone share a sample sketch for that board?

Take a look at this library : https://code.google.com/p/xbee-arduino/
This is the XBee Library for Arduino, you will find simple sketch that are perfect bases for the application you're trying to do.


text:
MMA7660 accelerometer with ATTiny85
I'm trying to make the ATTiny85 work with the MMA7660 accelerometer, so far, without any success. Google search for "ATTiny85 MMA7660" gives poor results, and I'm not sure it has been done at all, at least publicly, so I thought I'll try my luck here.
What I've tried is using the TinyWireM library, in different combinations. The last one is based on the MMA7660 Arduino library, specially adjusted to the TinyWireM, and taken from this post in Arduino forums (direct link to download).
The SCL is connected to PB0 and SDA to PB2, with 5k ohm pull-ups (I know that the recommended is 4.7k but this is what I have available, and I assumed it shouldn't make much difference).
I am using the Arduino IDE v1.5.6, which works successfully with other non-I2C attiny projects I have.
As for the final code I am using the .pde example that comes with the MMA7660, altered to use SoftwareSerial:
#include <TinyWireM.h>
#include <MMA7660.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(-1,4);

void setup()
{
  mySerial.begin(9600);
  MMA7660.init();
}

void loop()
{
  int x,y,z;
  delay(100); // There will be new values every 100ms
  MMA7660.getValues(&x,&y,&z);
  mySerial.print("x: ");
  mySerial.print(x);
  mySerial.print(" y: ");
  mySerial.print(y);
  mySerial.print(" z: ");
  mySerial.println(z);

}

The current problem with the above code is that the pointers just dump some memory without making any sense. If I try to see what TinyWireM.receive() command returns, values are 216 for all three variables. This is true even when I disconnect the MMA7660 from the prototyping board...! so I assume the problem is with the I2C itself, not working properly. The actual I2C address for the MMA (0x4C) and other relevant code is in MMA7660.cpp.
Any ideas?... Unfortunately I don't currently have another I2C device to examine the health of this protocol with my ATTiny85, so any experience you might have with this sort of configuration will be blessed.
EDIT: I marked dvlabsllc's answer as accepted answer since it gave me the right direction to pinpoint the issue further down the library path. I have opened a new question regarding TinyWireM library here.

I have run into similar frustrations using standard libraries and I2C.  I would have to look into the code and try it out on my own before confirming anything about this particular code; however, in the meantime you might want to try a tool such as I2cScanner that simply scans the I2C bus for all possible addresses and reports addresses that are "alive".  This (or something similar as I am not sure if you are using Arduino API) might be a good start to just see if the I2C is working and that you have the correct address.

I am using the Arduino API. Unfortunately it seems that the I2C scanner was built to use the Wire library, which relays on the Atmega328 built-in I2C chip. I will try to alter it to work with TinyWire.


text:
Keyboard/mouse libraries with UNO
I have an Arduino Uno Rev. 3 and I'm trying to make it so that the Arduino can send a key press / mouse action to the computer. However, these libraries are restricted to a few other versions of the board. Is there another alternative method to doing this without actually pressing any buttons/interacting with the arduino other than USB? Thanks!
Link

These at fist glance don't seem to be duplicates. However, the original question is basically the same thing, just suggesting a method for doing this. If you feel this isn't a duplicate, or you want another way (ex: PS2 mouse/keyboard support), feel free to edit your question and flag it for moderator attention so one of us can take a look at it. Thanks!

It is actually possible, but not easy.
The main MCU on the Uno, the ATmega328, is not capable of using the USB connection at a low enough level to make this possible. The other MCU on the Uno R3, the ATmega16U2, is. You can reprogram it to act as almost any arbitrary USB device.
Since the '16U2 has no connection to digital pins 2 and up or to any of the analog pins, you would have to program it to communicate with the '328 (or an external chip) via UART, and then have another program running on the '328 that would communicate with the other pins.
Note that you will need an external programmer for this, since once the '16U2 is reprogrammed you will lose the ability to program the '328 until you restore the original programming. Using another board running ArduinoISP will work for this.

A software approximation to low-speed USB using GPIO pins of the '328 itself and passives to sort of achieve the required USB voltages might be another option.

@ChrisStratton: The '328 does not have any access to the USB lines whatsoever, so you'd have to wire in another USB connector.

Yes, of course - but that also preserves the original one for development use, both loading programs and having serial debug output (which can be extremely useful when dealing with USB code).


text:
Arduino/Arduino clone board suggestions
I am planning to buy a Arduino board. I am also considering Arduino clones, too. My requirements are that the board should inbuilt communication modes like Ethernet, WiFi and a SD card slot, too. Also the board should have a decent amount of memory and the processor must be a a little more powerful than the Uno. The board must be capable of running a OS if possible!
I was looking at the Yun and Due. The Yun has all the communication modes but runs on a low end processor. The Due on the other hand runs on a ARM processor but has none of the communication modes. So now I am in a fix.
Which board should I choose?

Wait... the Uno can run Linux!!! Also, it's not a clone (and probably not on topic for this site) if it's not a replica of an official Arduino board.

I would go with a Yun. Despite having a low end CPU, it runs at 400MHz and the disk space can be expanded using the uSD card (see this blog post).
If you don't plan to make CPU intensive tasks (such as real time video streaming and manipulation), the Yun is a nice tool. Otherwise, the Tre fits better (however, at the time of writing, it still has to be released).

Can the YUN do multitaking ? Also do you have any ideas about arduino clones ?

@cache No, no Arduino board can do hardware multithreading AFAIK... You can do software multithreading... Also, it's not a clone if it's not a replica of an official Arduino board. Therefore, asking for a clone is the same thing as asking for a board.

The Yun can do multitasking on the Linux side only.

@FedericoFissore - untrue.  Multitasking is a software feature.  Things like having lots of memory, protection modes, or virtual cores etc certainly make it easier, but it's ultimately a function of the software, not the hardware.

@ChrisStratton agree. I thought cache was actually talking about multithreading (executing two different codes at the same time)

@all : My apologies. I wanted to do multithreading. So to execute that one would need the hardware capable to perform the task.

@AnnonomusPenguin : Yes i do understand what a clone means and i do have some clones too. These clones have the same architecture as the original but with added features.
Coming to the part where a UNO running linux , really ? It says here that "it takes two hours to boot up to a bash prompt, and four more to load up Ubuntu and login" If starting itself takes this much time, then when will i run my programs ?

@cache No, you're talking about a derivative. A clone is pretty much an exact duplicate (with a few minor changes). As far as the Linux computer, I wasn't saying it is viable, only that it is possible.

So as of now my best bet would be to get a YUN , right ?


text:
I²C with ATTiny85 at 8MHz using TinyWireM library
Hello fellow Arduino enthusiasts, I am trying to make the ATTiny85 talk I²C with a MMA7660 breakout board I have (it's an accelerometer, this is a follow up question to my previous one).
I would state in advance that the I²C chip works perfectly with Arduino Nano, that I am using the Arduino IDE v1.5.6-r2, using the arduino-tiny core (from here) and that until now I had no special issues working at 8MHz.
The official documentation for the TinyWireM library (at the Arduino playground website) states that:

By default the I2C master library (TinyWireM) is set to run at 1MHz.
  To run at 8MHz, #defines in USI_TWI_Master.h / .cpp must be changed.

I have made the following changes in USI_TWI_Master.cpp:
#define F_CPU 8000000UL // was 1000000UL

I have made the following changes in USI_TWI_Master.h:
#define SYS_CLK   8000.0 // was 1000.0
#define T2_TWI    1.3 // was 5
#define T4_TWI    0.6 // was 4

My guess is that the T2_TWI & the T4_TWI values are wrong. I also tried T2_TWI 40 and T4_TWI 32 (as stated here), and T2_TWI 2 & T4_TWI 1 (as stated here) but no luck. I also tried some other values in between that I thought might make sense but it won't work.
The code I am running is the I²C scanner from here (which as I mentioned works perfectly with the Nano and finds the device), the blow is a modified version for interfacing the TinyWireM library instead of the Wire library:
#include <TinyWireM.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(-1,4);

void setup()
{
  TinyWireM.begin();
  mySerial.begin(9600);
  mySerial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;
  mySerial.println("Scanning...");
  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    TinyWireM.beginTransmission(address);
    error = TinyWireM.endTransmission();

    if (error == 0)
    {
      mySerial.print("I2C device found at address 0x");
      if (address<16)
        mySerial.print("0");
      mySerial.print(address,HEX);
      mySerial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      mySerial.print("Unknow error at address 0x");
      if (address<16)
        mySerial.print("0");
      mySerial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    mySerial.println("No I2C devices found\n");
  else
    mySerial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

As a side note I would say that my logic analyzer was broken recently and I'm sure it would have helped here... Also I am aware of the sound-card hack to be used as logic analyzer, but would prefer to avoid adding more error-prone variables to the system, if possible, for now.
Here is a picture of probing with Saleae logic analyzer of the two channels. The result of the code above is "No I2C devices found":

(Full size picture)
Would appreciate the insights of anyone with experience using ATTiny85 at 8Mhz with I²C successfully.

Did you burn the fuses (upload bootloader) to enable the ATtiny to run at 8MHz?

@imjosh: yes. thanks for bringing it up. I am always using the same ATTiny for prototyping and from time to time I burn the fuses just to be on the safe side :)

I took a look at USI_TWI_Master.h, and I don't think T2_TWI and T4_TWI should be changed at all.  Just SYS_CLK   from 1000.0 to 8000.0.  Have you tried it like that?

Yes. I also tried with the original values. no go.

Are you using an external crystal or resonator?

I am using the internal resonator.

Try using an external crystal or calibrating the internal resonator maybe - https://www.google.com/search?q=calibrate+attiny+internal+resonator

thanks, but currently I'm looking for a solution that does not require external crystal. Also I could not find any reference on how to calibrate the internal oscillator (and not resonator, according to the spec). In addition I find it hard to believe that SoftwareSerial timing is right if the internal oscillator is not accurate enough.

Did you manage to successfully run I²C on ATTiny85 without external oscillator?

Let us continue this discussion in chat.

You have the Pull up resisters in place... both of them?

Yes. Both of them.

Any luck with this issue? I am probably experiencing very similar. My logic analyser says the first byte sent (the slave address) is correct, the rest is nonsense. I tried it on 1Mhz and 8Mhz, correct fuses, fiddling with the T2_TWI/T4_TWI but I am running out of ideas.

Unfortunately no. I also checked with logic analyzer and oscilloscope- and I can confirm output is garbage.

@Omer Looking at this picture from your post, are'nt SDA and SCL signals reversed? SDA looks like clock and SCL looks like data.

I have the same problem as you with a DHTC3 probe. The I2scanner code does not respond OK to the probe address with an Attiny85 while it works with an Arduino Uno. However, I changed the frequency to 8 Mhz and the 2 timers T2_TWI and T4_TWI. And you, have you solved your problem please?

You really just need to scope the signals, even if it's with a DSO Nano-type scope.
Without downloading the datasheets:

I would guess your pull-up is probably too small, but possibly too large (scope it)
Slew rate may be either insufficient or too steep (scope it)
Be aware that the ATTiny runs at "8MHz", and not 8.00MHz. The timing error can be off enough to cause communication issues at high speeds while working well at lower speeds (scope it, and/or start at default and incrementally increase speed by 0.5MHz until it stops working)
MMA may not support a typical protocol feature being used, i.e. 'repeated start', burst transfers, etc. (datasheet register/programming section)

Edit: Both the ATTiny and the MMA should have bypass capacitors near the power pins.

It's kind of easy to miss, but on my last comment to the question I mentioned that I did use logic analyzer and that the results are garbage. It happened with other I2C devices as well, not just MMA. Did you ever got the I2C working with the ATtiny85?

The Tiny family supports both "I2C" and "SPI", although they are not implemented as separate hardware peripherals. Instead, the Tiny has a generic hardware peripheral called the USI, that can emulate both.
Of course, both protocols can always be bit-banged for virtually 100% guaranteed communication with anything you want.

If you feel like it, could you hook up any I2C device up to one and post a capture from your scope?

I discovered that I have an MMA8451Q on my KL25Z. I will try to run it with the Tiny tomorrow and post back the results.

The USI part from Atmel documentation is what giving me hope. Unfortunately I never heard of anyone succeeding with it. I'll update my question with a screenshot of the probing.

uploaded the screenshot.

I know it's an old post, buy my ATTiny85 talked successfully to the BMP280 sensor via I2C using TinyWireM. And no, the SYS_CLK 8Mhz or 1Mhz doesn't make any difference. It works with any T2 and T4 for me - the 5 and 4 default (faster) or 40 and 32 (just slower). My issue was that I've bit-banged the LCD screen and then initialized via TinyWireM the BMP280 sensor... that mix doesn't work.

Just an idea. On adafruit.com there's a product called Trinket which is an ATtiny85 microcontroller board. It can communicate over I2C using their TinyWireM library. Maybe you should  check it out for reference. I hope it helps :)

The owner of the question has already mentioned they are using the library.


text:
Reducing lag between the arduino and a processing sketch on my computer
I'm currently on project #14 of the Arduino project book.
I'm trying to control a processing sketch on my laptop using my Arduino. This is accomplished by using a potentiometer to control the background of an image.
Arduino code:
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.write(analogRead(A0)/4);
}

Processing:
//imports serial library
import processing.serial.*;
//setups the serial object
Serial myPort;
//creates an object for the image
PImage logo;
//variable to store background color
int bgcolor = 0;

void setup(){
  colorMode(HSB,255);
  logo = loadImage("http://arduino.cc/logo.png");
  size(logo.width,logo.height);
  println("Available serial ports");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
}
//equivalent of arduino's loop function
void draw(){
  if(myPort.available() > 0)
  {
    bgcolor = myPort.read();
    println(bgcolor);
  }

  background(bgcolor,255,255);
  image(logo,0,0);
}

Now, while the code works, and the background color changes as i turn the potentiometer, there is a huge lag between turning the potentiometer and seeing the background change color, and the values from the Arduino/potentiometer change on the processing's serial monitor.
What I've tried:

Changing the speed of Serial communication

I've noticed that when I decrease the speed of Serial communication, e.g. around 100, the delay between turning the potentiometer and seeing it change on my laptop decreases to about 1 second. However, when I decrease the speed of Serial communication even further, e.g. a value of 1, the delay increases again.
On the flip side, at the standard speed of 9600, the delay is huge, roughly 5sec ++ before the changes in the potentiometer show up on the laptop/processing.
Why does decreasing the communication speed (up to a certain point) decrease the time lag, and increasing it increase the time lag? Also, is there anyway I can make it near instantaneous?

You're outputting a reading every single time round the Arduino loop(). It's quite possible that your Processing program isn't running fast enough to keep up with it. Try putting a delay into the loop() in your Arduino code to slow it down; e.g. delay(50).

Hi peter, thanks for the prompt answer, adding a small delay really did solve my problem. Just another small question though, is there any way i can determine the speed of my processing program in the future so as to prevent this from happening again, or does getting a better laptop/processing speed solve the issue? Also, why does entering a communication speed of 250 or 300 mess up the readings from the arduino?( the readings i get are alternate between the reading and zero E.g 147,0,147,0)

You're outputting a reading every time round the Arduino loop(), so it seems likely that your Processing program isn't running fast enough to keep up with it. Try putting a delay into the loop() in your Arduino code to slow it down, e.g.:
void loop(){
    Serial.write(analogRead(A0)/4);
    delay(50);
}

As far as I know, Processing aims to run at a consistent framerate, which you can modify using the frameRate() function. By default, it's 60 frames per second, although it may run slower on older systems (or where you're running an intensive program). You can check how fast it's running by reading the frameRate variable.
Introducing a 50 millisecond delay into the Arduino loop means it will be updating a little under 20 times per second. That means it should be fast enough for user interface purposes, but should also be well within the capabilities of your Processing program.
As far as the baud rate (communication speed) is concerned, adjusting it by arbitrary amounts is likely to have unpredictable results. That's because the hardware will only support specific speeds, and trying to use anything else can result in the data appearing garbled on the other end. The Serial.begin() documentation has some more information about supported baud rates.

As already pointed out, your Arduino is saying too much too fast. Adding delay() will slow it down, but still it keeps yelling at Processing. Ideally, you want Processing to ask for the value when it's convenient, and then receive one answer from your Arduino.
Enter SerialEvent().
As opposed to loop() on your Arduino and draw() in Processing, everything inside serialEvent() only excutes when there is something new in the serial buffer. So instead of Processing asking questions as fast as possible and your Arduino yelling back even faster, they can have a nice, polite (asynchronous) conversation.
Both Processing and Arduino have a serialEvent. This is serialEvent() on the Arduino and this is serialEvent() in Processing. Using serialEvent on both sides, this is what would happen:

Processing sends a character to the serial connection. This could be any character, but if we predetermine one we can filter out any unwanted requests caused by e.g. a noisy signal. For this example, let's send a V every time we want a new reading of your potmeter. After the character is sent, we continue our business as usual. Not waiting around for an answer here!
On the Arduino side nothing is happening, until it receives data in the serial buffer. It checks whether the incoming character is a V, and lucky us, it is. The Arduino reads the potmeter's value once, outputs that value to serial once, and goes back to chilling out, maxing relaxing all cool. Protip: terminate the value with a character (* in our case). This will help you in the next step.
Processing is doing its regular interfacey pixel business when all of a sudden there's a disturbance in the force new data in the serial buffer. It switches to serialEvent(), and starts reading the serial data, until our terminating * is encountered. Knowing for sure this was the last character worth reading, we can now store the incoming value in a variable that stores the Arduino's reading.
That's it. Processing now knows the new sensor value and carries on with whatever we tell it to do. Meanwhile, your Arduino is enjoying the weather or contemplating its existence until there is incoming serial data.

And while you're at it, put a capacitor in parallel with your potmeter. This smooths out little changes in your DAC's input, possibly preventing jittery motion in Processing.

Thank you for this nice (and kinda anthropomorphic) answer!

Actually, asking questions over USB can be a idea.  This is because USB has a lot more latency than a serial port, so asking a question and waiting for a response is a more time consuming operation than it would otherwise be, especially compared to what could be done at high baud rates.  Letting the Arduino run a little faster is fine (though it should not saturate the serial portion of the link); the catch is that the processing sketch should drain the Arduino data as it becomes available, and hold onto the last complete value to use when it needs one.

Your polling loop runs at full speed of your processor,
and writes to the serial port in each round.
This way, you're writing way more often to the serial port than it can handle.
The port writes out data as fast as you configured it, and buffer data that is comming in from your program too fast, to write it out as soon as possible.
It the buffer is full, it just drops new data.
What's important here is that it will keep the order of the values: It is a FIFO buffer, working in First In/First Out order.
What happens is:
The loop fills the port buffer, and keeps it 100% full.
If you turn the potentiometer, the changed value get's written to the end of the buffer, the port works as fast as it can to write out all elements in the buffer, that have still the old value.
And finally the value you are interested in. The most current value we wanted to see immediately was at the end of the FIFO, and first in/ first out also means last in/last out. The opposite of what we want.
The maximum frequency it makes sense to read your data, is the frequency you can write it out, so you should use at least a delay that is long enough to write out the bytes at the current port speed.

As another, independent measure to prevent this kind of delay in general,
 you could additionally set the write buffer of the port to a minimum.
That would cause data to be dropped much earlier, instead of buffering a lot first.
Of course, in many applications that is not what you need; With bad luck, it could work anyway in the beginning, and get unstable in some situations when the timing changes based on things like processor load, and there are only some random data samples that get dropped. A large buffer generally behaves much more deterministic, so do use a large buffer by default.

Right idea, but not quite right on the statement "It the buffer is full, it just drops new data.".  Once the buffer is filled, data is not dropped, rather the writes block until there is space in the outgoing buffer.   This means that the input and output soon end up flowing at the same average rate, but that there's a buffer's worth of latency in between them.

Instead of constantly sending serial data, only send data when the value of the potentiometer has changed over a certain threshold.
int oldValue = 0;
const int threshold = 5;

void setup()
{
  Serial.begin(9600);
  pinMode(A0, INPUT)
}

void loop()
{
  if(oldValue >= analogRead(A0)+threshold || oldValue <= analogRead(A0)-threshold)
  {
    Serial.println(analogRead(A0));
    oldValue = analogRead(A0);
  }
}

That loop() is not filling the output buffer with equal samples, that's good. But it still runs at full speed of the processor, which may be 100 times as fast as it's needed. That means it can still fill the buffer to the limit quickly if the input changes frequently, eg from noise above threshold, or a continuous change in high resolution (which is not the case in the example application here)

Two simple solutions that are guaranteed to work for anyone who is still looking:-

Increase the delay to 50 to 100 milliseconds.
Add this after the Serial.begin(9600) in setup();
Serial.setTimeout(50);

Step two is the most important. It worked for me only after I added the above code. This is not mentioned very often in many other forums that I have looked when I had the exact same problem.

This is somewhat mistaken.  The setTimeout() method applies to input, not output - see the documentation at https://www.arduino.cc/en/Serial/SetTimeout