text:
Short circuiting GND and power pins
I have created an arduino shield and i want to measure the voltage between the GND pin and 5V pins, to see if i see a voltage difference between the two points, in order to test if my pcb is fine.
My concern is since these are right next to each other and my multimeter probes are thick.
If the multimeter probe that 5V pin touches the GND pin, in other words, if i short circuit the 5V and GND pins, then will my arduino be safe?
I am afraid of damaging the arduino.

When I want to be sloppy with taking a ground point on Arduino I typically use the USB shield; it's hard to miss.  Is this all there is to the question or am I missing something?

My question is: If i short circuit the 5V pin, with the GND pin, will this damage my arduino?

@timemage The shield of the USB socket shouldn't be connected directly to ground. The Arduino breaks the specs by doing that. Instead it should be connected to ground via a large (1MΩ) resistor. This is so that when the plug is inserted the shield connects first and a current-limited path between the grounds is created first to balance the two ground levels. Only once that is done should the main power and ground be connected. So relying on the shield of a USB socket is not always a good idea...

how does testing the power supply voltage test the board? ... you would get 5 V without any board

@Majenko, I'm aware of how it is and can be grounded, e.g. that is often connected by capacitor as well.  All I'm getting it, is that in practice it makes a real easy to place to set a negative probe.

@timemage as long as you know your schematic it's fine. Yes, on the Arduino it's convenient. Except when it's covered with a shield ;) Or the great huge lump of metal shorts against pins on the shield above it...

@Majenko, it sounds like you want to have a conversation about this. =)

@timemage No, not a conversation. Just a moan about Arduino's shoddy design practices...

@Majenko i mean the 5V pin and the gnd pin. The shield is connected to them because the male header pins, go inside the female header pins of the arduino. I did not understand the 1MΩ part...

No, shorting +5 to Gnd is not safe, although a brief short might not cause damage. If it persists, you could burn a trace, overheat the voltage regulator, or damage the computer USB if that is what powers your Arduino. Most computers will sense that short and disconnect power to that USB until the short goes away, but you don't want to count on it!
If your meter has probes with clip-ends, use those to clip two bread-board wires, and probe the Arduino pins by plugging the wires into your shield. If the shield has no pin sockets installed, at least the bread-board wires are small enough not to short adjacent pins.

I hope i did not damage the arduino then. If i did damage it, then the arduino would not work at all? Because i did make a connection. How would i know if everything is ok?

If it was a brief contact, the board may well have survived. The most basic test is to load and run the blink.ino example. One that I use regularly is to write one that blinks each pin in sequence, then probe each pin with an LED and resistor to check that it works.

It all depends on how you are powering the board.
If you're running it from USB then the computer should shut off the power to the USB port. If it doesn't then the Arduino has a small self-resetting fuse on the USB power which should shut the power off for you.
However if you're powering through the barrel jack there's no protection. Worst case scenario: it will blow the voltage regulator, which then "fails short", meaning it passes the whole of the input voltage through to the microcontroller, which then kills it.
So yes, it's possible to damage the Arduino with a short circuit.
Most multimeters have a better way of testing the board though: either the "beepy" continuity test, or the resistance mode.  You can use that to test the continuity or resistance between your 5V and GND pins without having to connect the shield to the Arduino at all. 100% safe.

I am powering the board therough the computer's USB. However, you seem to have misunderstood. I did not explain this correctly. I don't want to test continuity. I want to measure between the GND pin and the 5V pin, to see if my voltage is indeed 5V (i was worried my shield pins do not touch the board).

Then again you can do that without power - test the continuity of the pins from the shield to the board.

mostly yes , mostly no . my old arduino got a little too much dusty and when i cleaned it with mild amount of water (nervously) and dried it partially . nothing happened to it . it was operating normally . but some beginner manuals tell not to short circuit it . dunno what's going on ...

I'm thinking you mean "partly" rather than "mostly". For what it's worth, pure water doesn't conduct all that well at all.  So if you haven't gotten sufficient salt, finger oils, soaps, or any other impurities, it may operate completely submersed.  I am not recommending that you try it.

oh , yes . that is why it didn't explode ...


text:
Power small hobby motor using Vin pin on Arduino and 9V battery, safe?
I want to power a small motor with a 9V battery and control it with PWM using an Arduino Leonardo. I know I can power the motor separately, but this introduces the problem of needing a battery to power the motor (9V battery) and another power source to power the Arduino (another 9V battery?)
Would it be safe to simply power the Arduino with a 9V battery and use the Vin pin on the board (which is unregulated and outputs directly the power source powering the Arduino) to drive the motor? That way, I power everything from the 9V battery, and use a transistor to drive the motor.
Thanks a lot!
Steve.

That should work. But you may have a problem with the small capacity of 5V battery, compared to AA or even AAA 1.5V batteries. I don't think that will be enough to drive a motor.

I will probably use a couple of AA instead. I'll calculate which type of batteries would be optimal for my project.

If you use a transistor circuit as shown below, back EMF would not cause any trouble.

Great! That's exactly what I was going for, assuming the +9V on the diagram is coming from that Vin pin on the Arduino.

You need at least an additional diode, see "purpose of the diode and capacitor in this motor circuit".

Yes it is  OK to do that. But the thing you should consider in mind is "What is the current requirement of the motor?"
You say

I want to motor a small motor with a 9V battery and control it with PWM

This means you have a servo motor, which might require a lot of current depending on the torque. So if you have a battery with low 'mAh', your battery will dry out very quickly. This might or might not be a problem for you depending on your requirements.

Woops I meant "drve a motor". It's actually not a servo but just a simple motor harvested from an old cd changer. I am aware that a 9V battery might not provide a very good battery life, but that is not my priority for now. As long as it works and is reliable all is good for now.

in that case, it would work just fine.

The arduino has its on voltage regulator, so feeing 9v to the arduino is not a problem. But the arduino will not drive the motor directly. You need to use a transistor big enough  to  hundle the amperage of your motor (e.g.tip120). The diagram above is a good indication of how to connect it. Yet the diagram is missing a diode (1n4001 or 1n4004) from the GnD to Vcc, as to avoid back voltage from the motor, which may damage your arduino.

source: Stack Exchange

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

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

sort: votes


text:
Is arduino starter kit disappearing?
It seems they stop the production of arduino starter kit (official), it's hard to find it on pro website.
Is there an other very good starter kit to start ? I mean I would like to try everything on small given project before starting my own project.

I haven't seen any information about the official starter kit being discontinued. Did you read an announcement about it?

it's out of stock in all the pro website I checked for a while now.

I suspect they're just struggling to keep up with demand. There are many alternative starter kits available from various sellers, depending on what you want to do.

AFAIK, it's still available on the arduino store website

Yes I know but you can only pay with paypal ..

AFAIK, Paypal accepts plain credit card payments even without an account, if that is your issue

Make has one: Getting Started with Arduino Kit v3.0

Can somebody confirm me it's a good kit ?

I can. Its got everything you need to get started.

I recommmend you this one: Beginner Learning Kit for Arduino, but they do not add the code here.

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


text:
Reading text/strings via processing
I'm trying to control an led attached to my arduino via key presses on my laptop.When i hold down a key, the led should light up, and when i release the key, the led should turn off.
While my code works ATM, i am wondering why my code will not work if i replace the numbers in my code with text/strings.
Processing code(Working)
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(8);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write(1);
      println("red");
    }

  }

}

void keyReleased(){
  myPort.write(2);println("released");
}

Arduino Code(Working)
int red = 7;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
  if(input == 1){
    digitalWrite(red,HIGH);
  }else if(input == 2){
    digitalWrite(red,LOW);
  }
}

Processing Code (Not working)
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(8);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write("red");
      println("red");
    }

  }

}

void keyReleased(){
  myPort.write("released");
  println("released");
}

Arduino Code(Not working)
int red = 7;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
  if(input == "red"){
    digitalWrite(red,HIGH);
  }else if(input == "released"){
    digitalWrite(red,LOW);
  }
}

From the above example, i get the error ISO C++ forbids comparisons between pointers and integers.After googling the error, it was suggested that i replace the double quotes with single quotes, after which the arduino code is able to compile, but the processing code gives an error "badly formed character constant(expecting quote,got e)".
I then tried changing using double quotes for processing and single quotes for the arduino quote, but predictably, it did not work.
Why does my code work when i pass numbers to the arduino via serial communication, and my code fails when i use text strings?

The problem is that you're mixing different variable types. It's kinda an oil/water scenario.
Basically, the serial.read(); command returns an integer, -1 if there's nothing in the buffer. If there is something, it will return the character code (i.e. 93 = a). Because of that, it's an integer. When you put something in single quotes, it compiles as the equivalent ISO character code.
So, when you do input == 2, it is integer [compared to] integer. When you do input == "string", you're doing integer [compared to] string, thus you get errors. BTW: a string is a type of pointer.
So, what you have to do is this:
string input = "";
if(serial.avaliable()) {
    delay(100); //Wait for all data to be received
    while(serial.avaliable()) {
        string = string + char(serial.read());
    }
}
if(input == "yay_it_works!) {
    //Done!
}


text:
arduino due-Python interfacing for high speed data rate
Four our project, I want to send data mesured by an Arduino due to a computer via Pyton very vast. So I tried to make a simple benchmark by sending 10240 int datas to determine the time it take. In order to do this, I first try using the programming port and execute this simple script:
int i=1;
int maxv=10240;
int value[10240];
int deb, fin;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(250000); //serial initialisation
  for (i=0 ; i<maxv ; i++){
    value[i]=i;
  }
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("starti"); //flag
  deb=micros();
  for (i=0 ; i<maxv ; i++) { // sending loop
      Serial.println(value[i]);
  }
  fin=micros();
  Serial.println("stopi");
  Serial.println((fin-deb)/1000000.0);
  delay(2000); //waiting
}

So with this I can mesure the time it take to send all the datas. And I receive it with this Python's script:
import numpy as np
import serial
ser = serial.Serial('/dev/ttyACM0', 250000)

value=np.empty(10240)

temp=ser.readline()

while temp!='starti\r\n': #search for the flag
    temp=ser.readline()

for j in range(10240):
    value[j]=int(ser.readline())

ser.readline()

time=float(ser.readline())
print time

with this beaudrate, it take nearly 2.4s which too slow for my purpose. If  try another baudrate, 500000 for example I read data like this : �Ë$Pd@s`¥š... I have this for all baudrate higher than 250000.
So I tried the native port which normaly send the data as fast as he can, but we this it took nearly 1.3s, and it's again too slow for my purpose.
I checked that it is not python wich is too slow, by doing the same than in the last example:
import time
import numpy as np

value=np.empty(10240)

deb1 = time.clock()

for j in range(10240):
    value[j]=j

fin1= time.clock()
print fin1-deb1

and it took only 4ms. So is it clearly the arduino wich send the data to slowly.
So how can I increase the data flux? I have seen the serial.write(buf,len) function which seems does not convert the data into ascii caracters. Does this function will be faster by putting the correct arguments? And, if it's the cas, how can I read this with Python?

There's two things you need to know:

The Serial.write(buf, len) function sends the raw data - one byte for every "len" count.
On the Due integers are 32-bits, so each one takes 4 bytes.

So first you need to define how big the numbers are you'll be dealing with and use data types that are big enough without being wasteful - you have 3 choices: char, short and int - 8, 16 and 32 bits respectively.

Values between 0 and 255 use an unsigned char (uint8_t)
Values between -128 and 127 use a signed char (int8_t)
Values between 0 and 65535 use an unsigned short (uint16_t)
Values between -32768 and 32767 use a signed short (int16_t)
Values between 0 and 4,294,967,295 use an unsigned int (uint32_t)
Values between −2,147,483,648 and 2,147,483,647 a signed int (int32_t)

One very tricky thing with this kind of binary data transfer is knowing where a value starts and ends.  You don't get that kind of issue with ASCII representations as you have a line feed and/or a carriage return after each full value and the range of valid characters that make up a value is very narrow and can never contain the delimiting character.  You don't have that luxury with binary transfers as there is no byte value that can't appear in a data stream.  However, there could be byte sequences that could never appear in the data stream - numbers you know you'll never be using that could form part of a synchronizing header (say, in hexadecimal, 0xFF 0xFF 0xFF 0xFF 0x00 0x00 0x00 0x00 - or in signed shorts that would be a sequence of 65535 65535 0 0) - once you see that sequence of bytes you know you're lined up with your data stream and can receive it byte by byte and build up the right sized values from that.
You can estimate your transfer time by working with the baud rate and knowing the data size.  For instance, to transfer 1000 short (16 bit) values at 250000 baud should take around:

1000 * 2 = 2000 bytes
250000 baud = 25000 bytes per second (8 bits for the byte, 2 bits for the start and stop bit)
2000 / 25000 = 0.08s

Ok, let say I want to send 1000 short as you suggest. Which function I should use to access the 0.08s for time transfert you told? The Serial.write() function or an another? Do you have a simple example?
Thanks

Yes use serial.write.

@Majenko: I didn't realize that int on the Due takes a whole 4 bytes. I suppose that's related to the difference between a 32-bit and 8-bit processor? Would a byte variable then also take twice as much space compared to the Uno? I'm surprised I didn't run into any obvious problems from this.

@jerry no a byte is always a byte, I.e., 8 bits. A byte is a basic unit, an integer is a numerical concept. Ints in c come in two basic sizes: short and long. Short is 16 bits and long is 32 bits. Unless you specify a size the default is used. On 8 bit systems a long takes a lot more processing than a short, so a short is the default. The opposite is true on 32 bit do a long is the default.


text:
Going from arduino & sketch to production
I've got a little proof of concept thing going here with an arduino & Ethernet shield. The basic idea is for it to ping out much like a heartbeat monitor every so often so I can see if my house still has internet connectivity.
The arduino works nicely and does exactly what I want. I've ordered a board to be made with just the basic components needed and now want to put the code on to it. They gave me an option to load the code (Dragon AVR) during checkout and I'd love to try that out. So, the question is - how on earth do I package up code for something like that? I've seen a number of people ask the same thing for large manufacturing scales / similar setup where they don't fancy using the arduino & IDE as a programmer.
I've asked around on IRC and various other places but nobody seems to be able to give me specific and clear advice on whether it's possible and how to go about doing it.

Don't forget to also provide the fuse settings. Fuses on the Arduino are different from those that are set when the chips leave the factory.

@Gerben how would I be able to define that?

Not sure. It's just 3 bytes, so you can just send them the three values I suppose.

"Intel Hex" is pretty much an industry standard and I'm quite certain the .hex files produced by the GNU AVR tools is Intel Hex format. Your vendor is almost certainly prepared to load your sketch from the .hex file.

Have to agree. But it can't hurt to ask if they can support the ELF file as well.

Thank you, thank you, thank you for not replying with "easy" and that's it! If you don't mind me asking, the hex file that is produced when I load my sketch onto the arduino should be "build ready"? I.e just ship them that?

Or how do I generate the ELF? Sorry guys!

Both files are products of the compile/load process. If you're using the Arduino IDE, I can't help you much with the locations of those files (though I'm sure someone here knows, for whichever OS you use). I know the Eclipse IDE puts those files in a folder named for the board or configuration, within each particular project.

Whenever I program my chips using ICSP I always use the exact same .hex file that is output by the IDE. I hope you have an ICSP header on your board in case you ever need to change the code.

That sounds promising. Literally just lift the hex file and away we go? Is it that simple?

Check with your vendor to be sure, but probably, yes.


text:
How do I send an arduino PIN state to a local PC using the ethernet connection?
As a PIN goes high I need to trigger an event that will send the IP or MAC of the arduino and the PIN state over the wired Ethernet to a local computer. I am using an Ethernet shield to send and receive from the arduino but I am stumped on how to send and process the information at the PC. I will have 42 Arduinos on the network all set to send PIN information over the wired Ethernet. Sounds simple but after a days research I am now looking at other solutions.  I currently have the faithful Uno with the network shield as my prototype. For the final install I can purchase any of the arduino range like the Yun,Duo etc. if this would help. Any direction would be welcomed.

Both of the comprehensive answers by Majenko and Damiano Verzulli are good, but I would be asking if you want to push or pull the information from the 42 Arduinos. To  push it you want to make them HTTP clients and have them contact a central server when the pin changes. To pull the information they need to be HTTP servers which a central client polls from time to time. It might be easier for the Arduinos to establish a telnet connection and send (push) information that way.

The simplest method is to set up a web server on your PC.  You haven't mentioned what OS you run (which is kind of critical), so looking into WAMP or LAMP ("Windows/Apache/MySQL/PHP", or "Linux/Apache/MySQL/PHP") is probably your best option.
Once you have a working web server you can pretty much use verbatim the Ethernet examples for connecting to a remote website ("Web Client").  That website would be your local PC address, and you send whatever parameters you want.
You then write a small PHP script (or whatever language you program your chosen web server in) to accept that web request and process it accordingly.
In general you never need to explicitly send the IP address since it is encapsulated as part of the actual socket connection information and is generally made available through various means to your web page (see $_SERVER in PHP for example).
If you want to get more "low level" and lighter weight then you would most likely be looking at writing a UDP server on your computer which receives UDP requests from the Arduinos and processes them as needed.  The content of a UDP request is entirely up to you, but programming a server for dealing with it is beyond the scope of an answer here - suffice it to say there are plenty of resources online available for all the major operating systems and programming languages on how to write UDP servers.

In my opinion, a perfect solution for the "As a PIN goes high I need to trigger an event" problem is brought by interrupts. In the official documentation I read: "...Arduino has two different kinds of interrupts: external, and pin change..." and the latter seems very suited for your needs. So my idea (but, please, be aware that I'm not at all an Arduino developer... yet) is to simply develop an "interrupt-handler routine", and properly attach such a routine to your PINs. There are plenty of details to analyze (as well as plenty of documentation about Arduino interrupt handling) but... the idea should be clear.
Please, while developing such a routine DON'T be tempted to push all of your networking code inside the routine itself: for reasons deeply and clearly explained by @NickGammon, interrupt handlers should be executed as fast as possible. Here follow an important part of Nick's article:

[...]
Hints for writing ISRs
In brief, keep them short! While an ISR is executing other interrupts cannot be processed. So you could easily miss button presses, or incoming serial communications, if you try to do too much. In particular, you should not try to do debugging "prints" inside an ISR. The time taken to do those is likely to cause more problems than they solve.
A reasonable thing to do is set a single-byte flag, and then test that flag in the main loop function. Or, store an incoming byte from a serial port into a buffer. The inbuilt timer interrupts keep track of elapsed time by firing every time the internal timer overflows, and thus you can work out elapsed time by knowing how many times the timer overflowed.
[...]

As for the "...will send the IP or MAC of the arduino and the PIN state over the wired Ethernet to a local computer...", @Majenko already answered that "source IP" and "source MAC" (of your Arduino) are not needed to be sent explicitely by your application, as if you're using an Ethernet shield (...and, on top of it, the IP protocol stack) it will be the shield itself in dealing with the "encapsulation" process, by which your data (the data "sent" by your own code) will be encapsulated in a proper Ethernet frame (that will include the source MAC) and a containing IPv4 packet (that will include the "source IP").

As for the "...send [the] state over the wired Ethernet to a local computer..." you're missing some very important details, like which operating system your local computer will be running and, more important, which programming language are you using to write your "server-application code".
The LAMP/WAMP approach proposed by @Majenko is relatively easy to implement, as the WebServer (Apache) will bring you a ready-made approach to handle network requests: afterall, you need a "server" application (an application "listening" to a socket, waiting for incoming messages/requests coming from network clients) and a web-server like Apache is exactly such an application.
Anyway, should you need something more specifically suited for your needs, nothing prevent you to write your own "server". There are plenty of libraries for plenty of programming-languages.
As I'm confident with PERL, I suggest you checking one of the many tutorial describing PERL client-server programming. Please note that PERL is a cross-platform language, supported also on Windows systems.
A final note: While implementing your "server-code", please check/consider if you need a "blocking server" (one who can handle only one single request at a time) or a "non-blocking server" (one who can handle multiple requests, coming from multiple arduinos, at the same time).


text:
Storing array in PROGMEM
I have an array of a lot of numbers (1 and 0) but i can't store them since arduino does not have enough space. How can i save an array of example 00110 in PROGMEM, then read from PROGMEM and set x to be equal lets say, third int in the array?

How many is "a lot", and how wasteful is the datatype you have chosen?

4000 elements and each element is a number like 1 or 0 to set a pin high or low.

Stored as int variables (as you seem to suggest) that's a massive 8KB.  Packed into individual bits of a byte that's a mere 500 bytes.

I can store it in PROGMEM

The Arduino website tells you all about how to use PROGMEM.  Have you considered reading that? https://www.arduino.cc/en/Reference/PROGMEM

Yes i didn't understand it well i need a code for my case

There is suitable code right there on the page for you. What more do you need?

Can you please send me the part of the code for storing an Array of 1's and 0's and then setting a variable as a value from that array?

Look at the bits of that code pertaining to the variable "charSet" - it has everything you need.

It's not about storing array but declaring const char PROGMEM myarray[50] = {0x45, 0x47}; in source code , etc. It's elementar task appearing in many examples.

After i store the array in PROGMEM how do i set a variable to have a value of a element inside that array?

Store them with const byte PROGMEM with bit 0 as MSb and bit 7 as LSb per byte. E.g. 011100100101001010101011 would become const byte[] var PROGMEM {0x72, 0x52, 0xab}
Use the following macro to retrieve them (untested):
#define loadbit(mem, pos) ((pgm_read_byte(&(mem[pos / 8])) >> (7 - (pos % 8))) & 0x01)

So if you had const byte[] data PROGMEM {0x72, 0x52, 0xab}; you would call loadbit(data, 3) and it would return bit 3 starting with 0 on the left, i.e. 1.
Naturally if you needed more than one bit at a time there are probably situation-specific routines that could be used, but without knowing anything about the actual program the above will work.

What data type is that? 0x72? Is that hex? And how do i convert big data chunks of binary into that data type?

8 bits at a time.

@Arduino I usually write a Perl or PHP script (depending on what the source of the data is) to convert it into C source code.

As noted in Ignacio's answer, you can pack your bits of data into bytes and access them via pgm_read_byte() calls.  If (for coding convenience, not for efficiency) you prefer to pack the bits into larger units, you can use word and dword access functions, as listed in AVR pgmspace.h documentation.  The _near and _far suffixes denote 16 or 32 bit pointers, respectively; for an Uno with its 32K flash memory, _near is always suitable.  See PROGMEM documentation at arduino.cc for further discussion.
Here's an example program that accesses and prints data from program memory in 16-bit chunks:
void setup() {
  Serial.begin(115200);         // initialize serial port
}
int k=0;
const uint16_t fnums[] PROGMEM {191, 272, 353, 434, 515, 646, 767, 888};
void loop() {
  uint16_t b = pgm_read_word_near(fnums+k);
  Serial.print(k);  Serial.print(" ");
  Serial.print(b);  Serial.println();
  k = (k+1)%8;
  delay(1000);
}

To pack your 4000 bits of data in the first place, write a C or Python program that runs on a host computer and writes out array definitions that you can cut and paste into a sketch.  Here's an example (in Python) that packs bits into bytes:
data = [1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1]

first = 1; byt = 0
for i, b in enumerate(data):
  if i%8==0:
    if first:
       print 'const uint8_t fnums[] PROGMEM {',
       first = 0
    else:
       print '{},'.format(byt),
       byt = 0
  byt = (byt<<1) | b        # add bit into byte being built

print byt<<(8-i%8), '};'

Here is what the program produces:
const uint8_t fnums[] PROGMEM { 197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 262 };

If you want that code to instead pack bits into 16-bit words, change 8 to 16 in four places.  Note, the code stores bits in the “bit 0 as MSb and bit 7 as LSb” order mentioned in Ignacio's answer.  Thus, data[0] is stored in the high bit of fnums[0], data[8] is stored in the high bit of fnums[1] , and so forth.

The thing is that (E)LPM only loads a single byte at a time regardless, so using larger types causes the program to do more work for no gain.

Yes, I meant to mention that byte access uses fewer instructions.   However, for some kinds of data (not necessarily this data),  coding convenience rather than efficiency may be important.  Added a note to answer.

How do i convert bits into bytes like in vazquez-abrams example?

@Arduino, see edit.  Also, upvote answers you find useful

Building on the excellent other answers by jwpat7 and
Ignacio Vazquez-Abrams, you could conceivably convert your bits into a table using Lua:
data = { 1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,
         0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,
         1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,
         0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,
         0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1 }

output = 0
bit = 0

for _, num in ipairs (data) do
  assert (num == 0 or num == 1, "Number must be 0 or 1")
  output = (output * 2) + num
  bit = bit + 1
  if bit >= 8 then
    io.write (output .. ", ")
    output = 0
    bit = 0
  end -- if
end --for

print ""

Output from above:
197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,

Now you can make a simple function to pull a particular bit out of PROGMEM:
const byte myTable [] PROGMEM = {
  197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,
  };

bool getBit (const unsigned int which)
  {
  const unsigned int whichByte = which / 8;
  const byte whichBit = which & 0x07;
  return bitRead (pgm_read_byte (&myTable [whichByte]), 7 - whichBit);
  }  // end of getBit

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

  for (int i = 0; i < sizeof (myTable) * 8; i++)
    {
    Serial.print (int (getBit (i)));
    Serial.print (", ");
    }
  Serial.println ();
  }  // end of setup

void loop ()
  {
  }  // end of loop

Output from above:
Starting
1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,


text:
Unable to light up all the LEDS connected to Arduino using processing
I have 3 LEDs connected to my arduino which are controlled via laptop key presses with processing.
While the LEDs are able to light up when the respective buttons are pressed, i am unable to light up all 3 LEDs simultaneously when i press all 3 keys at the same time. I am however able to light up 2 LEDs by pressing 2 buttons simultaneously.
All the LEDs light up when their respective buttons are pressed, so i know that it is not a defective LED and/or faulty connections/wiring at play but something else that is causing the issue.
My processing code:
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(64);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write(1);
      println("red");
    }
    else if(key == 'y' || key == 'Y'){
      myPort.write(2);
      println("yellow");
    }
    else if(key == 'g' || key == 'G'){
      myPort.write(3);
      println("green");
    }
  }

}

void keyReleased(){
 if(key == 'r' || key == 'R'){
      myPort.write(4);
      println("red released");
    }
    else if(key == 'y' || key == 'Y'){
      myPort.write(5);
      println("yellow released");
    }
    else if(key == 'g' || key == 'G'){
      myPort.write(6);
      println("green released");
    }

  println("released");
}

My Arduino code:
int red = 7;
int yellow = 6;
int green = 5;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
   pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
    if(input == 1){
      digitalWrite(red,HIGH);
    }
    else if(input == 2){
      digitalWrite(yellow,HIGH);
    }
    else if(input == 3){
      digitalWrite(green,HIGH);
    }
    else if(input == 4){
      digitalWrite(red,LOW);
    }
    else if(input == 5){
      digitalWrite(yellow,LOW);
    }
    else if(input == 6){
      digitalWrite(green,LOW);
    }
}

Things i've tried.

I've tried increasing the buffer size from 10(initially) to 64(in the code above)
I've tried increasing the baud rate from 9600 to 12000, just in case it was the serial information not being read fast enough.

None of the things i've tried, listed above, was above to solve my problem, and i dont see what could be causing the problem.
Any advice would be much appreciated.

could you include a screen dump of your serial port? ie, whilst you have the serial monitor open, press the keys in the sequences you're interested in, eg (CAPs is on, lowercase is off): RrYyGgRYryRYGrygYGygGYRgyr as I said, as an example. Then check to see if the serial data is as you'd expect. ie, in the above example you should see: 1425361245123456.... and so on

I'll add, I thought initially it might be a limitation of the keyboard, ie three main characters (ie not modifier keys) probably can't all be registered at the same time, but I just tried it on my Macbook Pro keyboard and it did, if you have an onscreen keyboard viewer, see if all the keypresses register as expected.

I'm unable to open the Serial monitor on my Arduino as i get the error Serial port already in use, try quitting any programs that might be using it. I suspect it is because i'm running the processing sketch. However, i've been looking at the processing display, and the when i press 3 keys, the 3rd key does not print to the screen.(e.g when 'g' is the 3rd key pressed,"green" is not printed to the screen). I'm not sure why it works on your Macbook Pro, but i'm guessing the problem lies with my laptop's keyboard's limitation in that it does not register 3 key presses at once!

what hardware and OS are you using? 2) You could try changing your keys, use the modifier keys instead, you should be able to press any combination of shift, control, option/alt, and windows/command. It's usuallt even possible to determine left from right modifier keys.

I'm guessing it is a hardware issue as I discussed in the comments above.
I have just set up a breadboard and copied your code verbatim into the Arduino IDE and Processing (I edited the port index to use). It works as desired. Pressing R, G, or Y will turn on the respective LED and releasing it will turn it off.
I can press these three keys in any combination of none on, one only, any two, or all three, and the LED gives the expected result.
Keyboards were not initially designed to have multiple "main" keys pressed down at any one time, the exceptions to these being the modifier keys (Windows/Command, Option/Alt, Control and possibly some others (I'm thinking the older keyboards here that had "other" keys—Scroll Lock, Print Scr, etc—I'm really unsure).
It appears now, that some hardware and software may have overcome this. As I've said, your project works fine for me. Also, you could try three different keys, it could be a result of how the keys are scanned and you may stumble across three that don't interfere with each other.
As I've suggested in the comments to your question, modify the code to utilise the modifier keys instead, or use the keyboard keys as toggles (ie press once for on, press again to turn it off).


text:
Significance of the numbers used in the manual
i just bought the starter kit and am currently working my way through the examples in the book when i came across some numbers used in the manual that seems a little too specific.
For example, in project #3,the love-o-meter, i had to divide the sensor value by 1024.0, and the explanation for it was never given in the manual.
Furthermore, in project #4(which i'm currently at), the book states that i have to convert sensor readings from 0 - 1023, to a value between 0 to 255.Is the number 1024/1023 simply an arbitrary number/limit set by the sensor's manufacturers? Also, is they any significance or reason that analogueWrite only accepts positive values up to 255?
Thanks!

The range 0 - 1023 comes from the analog-to-digital converters (ADC) built-in to your Arduino. What they do is take a voltage reading (e.g. from your sensor) and compare it to the analog reference voltage (which is typically 5 volts, although it can be changed).
It converts that reading to a binary number. The ADCs on board a typical Arduino have 10 bits of precision. The maximum number you can represent with 10 binary bits is 1023. Therefore, a reading of 0V is converted to the number 0; a reading of 5V is converted to the number 1023; and so on (it handles all the in-between values too).
However, analogWrite() works quite differently. It's not actually producing a varying voltage on the output (i.e. it's not true digital-to-analog conversion). Instead, it's using Pulse Width Modulation (PWM) to do something similar.
That means it sends lots of 5V pulses on the output in quick succession. The 0 - 255 values you give it affect the duty cycle -- that is, how long each pulse is compared to the gaps between pulses. The longer the pulses are, the 'stronger' the signal is. This is very useful for applications such as controlling the brightness of an LED or the speed of a basic DC motor.
The PWM signal is controlled by timers built-in to the microcontroller. I suspect it's the capabilities of those timers which determine the input range for analogWrite().
You can get more information from the online documentation for Arduino:

http://arduino.cc/en/Reference/AnalogRead
http://arduino.cc/en/Reference/AnalogWrite

It's the minimum of the timer capabilities. The 8-bit timers are naturally restricted to 8-bit PWM precision, but even the 16-bit timers are reduced to 8-bit precision for consistency's sake.

To clarify, analogRead() has a 10 bit range due to the arduino's Analog to Digital Converter, or ADC. 10 bits can store 1024 (2^10) different values; counting zero as a value gives the range 0-1023.
In arduino 0 is the reading when a pin is grounded, 1023 is the reading when an analog pin is connected to Vref, or 5v if there is nothing wired to Vref. The sensors provide a voltage somewhere between these values, but not the actual numbers your code gets.
analogWrite() accepts 8 bit numbers. That is 2^8 or 256 different values, called 0-255. It only simulates an analog voltage by pulsing a pin rapidly.
In short, the numbers are not arbitrary, but express the limits of the arduino chip's IO. They look random because they were written in decimal, but in binary they are very simple. If you are interested, you could look into replacing the decimal numbers in the code with hexadecimal numbers, which make their binary representations very obvious by way of 16 being 2^4.

More explanation: binary numbers are different than base 10 as you probably know. The meaning of those numbers is simple.
Start with 1 and double it. Keep doubling. You will soon hit 256 (computers start at 0 not 1,  so you have to take that into account, 0-255 is 256 different values). Keep doubling and you will soon hit 1024 (0-1023).
So these numbers are not arbitrary, they are Base 10 (0-9 like you learned in school) representations of Binary Numbers, more specifically, the high limit a given length of binary digits can represent before having to add another digit.
1111111 is binary for 127, with 0 thats 128 different values those 7 digits can represent. To get to 255, you have to add a digit for 8 total digits, 11111111 = 255. 9 digits or 111111111 = 511 and ten digits or 1111111111 = 1023.


text:
Explanation please, of hardware and software serial links
I am starting to use a Seeeduino GPRS shield (please see note), which is essentially an Arduino Leonardo that, among other things, can be used as a mobile 'phone for sending and receiving texts. I have successfully tried the "blink an led" and "fade an led" sketches, so the compiling and uploading are ok
I am using a desktop computer with Linux Fedora 20.
Now I want to go on to use the cell phone network to communicate with my mobile 'phone. However I am puzzled by something I assume everybody else understands already, and that is the references to "select either software serial port or hardware serial port to be connected to GPRS Shield". Please could someone explain what "software or hardware serial port" is, in simple terms, or point me to a web site that does so? Do I need any wired connection with my PC other than the USB link I use for uploading sketches?
Note: I bought a discounted GPRS shield labelled version 1.0a2. All the information on the 'net is of version 1.0 or 2.0 (with no "a2") and photos and diagrams do not correspond with what I have. I am awaiting official documentation, but meanwhile treating it as an Arduino Leonardo seems to be working.

The Seeeduino GPRS shields version 1.0 and 2.0 are just shields. They do not contain an Arduino MCU and don't have a USB, and so will not function as an Arduino. As you say, yours is a bit different and does function as an Arduino. This may be the source of your confusion with the guides, as they assume you are plugging the GPRS shield into another Arduino. Please post a picture of the board.

Most small micro controllers, AVR's included, have dedicated hardware for communicating with different serial devices. In arduino these are referenced with "Serial", "Serial1", "Serial2" and so on, depending on how many hardware serial ports your particular arduino has.
Leonardo's are an exception, the first hardware port is "Serial1" and "Serial" refers to the PC's usb connection. On the other arduinos that I know of "Serial" is hardware serial used for PC comms, so using it for other hardware requires sacraficing your PC link.
Software serial ports use the processors more generic pin-change interrupt system to communicate on any pins that support said interrupts, but they have a higher processing overhead and often cannot support the same high speeds as the hardware serial. There are different libraries for Software Serial that have different approaches giving different advantages and drawbacks.
To use a software Serial port you will need to make one to be used in your code, which will look something like this, depending on the type name the library you include uses:
SoftwareSerial softSerial( txPinNumber, rxPinNumber);

So in short, your processor has dedicated hardware for communicating over serial that should be used first, but if you need more ports the processor can simulate some extras which is referred to as "Software Serial". The documentation to your GPRS shield implies that either will work just fine. You should look at the arduino documentation for your board to see how many ports you have and which pins can be used for serial.
The documentation does not imply you will need any special link to your computer outside of the USB connection.

Yes - if this were at ATmega328p-based board like an Uno, the hardware serial is already used for the PC connection, so serial peripherals usually go on a software serial if they cannot be permitted to block PC communication.  But on a Leonardo type board as in this question the hardware UART is free and so can be "used first" as you recommend.  Similarly, if the board were a Mega, there would be multiple hardware UARTs, some possibly free.

A SoftwareSerial connection is created using the UART pins 7 and 8.
Having the device in HardwareSerial mode allows the device to connect to pins 0 and 1, allowing direct control from the serial connection to the computer.
In SoftwareSerial, you can communicate with the Arduino Via serial, and the Arduino controls the GPRS shield via uart.

Software serial can be on any GPIO pins.  And the Leonardo-type board in this question does not connect to the computer via a UART on pins 0 and 1, but rather via the on-chip USB interface.

The hardware serial port is the serial port which connects to the computer this takes up pins 1 and 2 I believe. You can read about this here http://arduino.cc/en/reference/serial.
Software serial ports are only on digital IO pins. You can read more about this here
http://arduino.cc/en/Reference/softwareSerial
You should not need anything other the USB connection port.

The question concerns a Leonardo-type board, where the computer connection is not via the UART pins, but rather via the on-chip USB interface.


text:
What do I do about a compiler error " variable 'font' must be const"
I am trying to run the test program from Adafruit, with their libraries, for an Arduino controlling a Nokia5110 display and get this error message:
Arduino: 1.5.8 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"

    /home/Harry/Arduino/libraries/Adafruit_GFX/glcdfont.c:9:23: error: variable 'font' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char  font[] PROGMEM = {
                           ^
    Error compiling.

Please can anyone explain this? I can happily give more details, but I am not yet sure how much is needed and the files are rather too long to include them all at this stage.

Include you FULL code.

Looks like this was already fixed. Are you using an old GFX library?

The error already says what you should do, and even points to were you need to add it.

The problem is you're using an old version of the Adafruit GFX Library, which was written for a previous version of the Arduino IDE. You just need to install the latest version of the library and your problem will be solved:

Download https://github.com/adafruit/Adafruit-GFX-Library/archive/master.zip
Unzip the downloaded file.
Rename the unzipped folder Adafruit_GFX
Replace /home/Harry/Arduino/libraries/Adafruit_GFX with the folder.

If you run into any other problems after doing that I recommend trying the latest version of the Arduino IDE. The version you're using is very outdated.

You can not change variables in PROGMEM memory.
Therefore the variable must be a const variable.
This way the compiler can check whether you try to change the value or not.


text:
How do I deal with this Arduino IDE installation error?
I am using Linux Fedora 20 (yes I am going to upgrade it, definitely, soon) and I have installed arduino-1.8.0, but I get this message ...

Your copy of the IDE is installed in a subfolder of your sketchbook.
  Please move the IDE to another folder

... when I click on the desktop icon, or run ./arduino. I have tried moving the tar.xz file to its own folder ArduinIDE again installed it but get the same message. Please,what should I do to get out of this? Please no answers like "just do what it says":in that case what do I move, and what criteria does the destination need to have?

Delete (or edit) your preferences.txt file - it most likely has your sketchbook folder set to your home directory.
You may find it in ~/.arduino15 for the "real" Arduino IDE, or in (I think) ~/.arduino for the arduino.org one.
Unless you have a specific reason for wanting to run 1.8.0, which is actually 1.0.6 re-numbered, you should be using the version from arduino.cc which is currently 1.6.13.

Thank you Majenko. I uninstalled 1.8.0 and installed 1.6.13 instead, then the problem was cured when I altered the line in my home directory /home/Harry/arduino15 from sketchbook.path=/home/Harry/ to sketchbook.path=/home/Harry/Sketchbook

"1.8.0, which is actually 1.0.6 re-numbered" This is incorrect. You're thinking of the arduino.org 1.7.x releases. The 1.8.x releases started after the legal dispute was resolved and .org started using the .cc IDE again. They jumped straight from 1..6.13 to 1.8.0 to avoid any confusion with those 1.7.x releases. 1.8.0 was released Dec. 20 '16.

This fixed it for me. Funny thing is that in my case I have Arduino IDE run inside a VM (VirtualBox), which crashed (I had to restart the host due to some reason). Before the crash I didn't have a problem but after that I did. Note that in my case the sketches were in a completely different folder: /home/user/ArduinoProjects, while the IDE was in /home/user/Arduino.

This is still happening. The exception message is not clear. It is objecting to being installed in "the same folder as your sketchbook", not in a "subfolder of the sketchbook".  It should ideally read...

Your copy of the IDE is installed in the parent folder of your sketchbook.
  Please move the IDE to another folder.

You should be able to put side by side versions in /opt or create another branch in your home folder.


text:
In Linux how do I start up Atmel Studio
I am using Linux Fedora 20. In order to compile C programs for the Arduino, as described in the book "C Programming with Arduino" by Warwick A Smith, pub by Elektor, I have downloaded and untarred/unzipped "avr8-gnu-toolchain-3.5.1.1671-linux.any.x86.tar.gz". That's as far as I can get. Please how do I proceed from this point? Is there anything else I need or should have done?

What you have there is the compiler. If you want the IDE you should download and install the IDE.

You do not need atmel studio to do C development for the AVR - you can use any text editor or configurable IDE along with a toolchain such as avr-gcc (possibly what you just downloaded).  You can even "borrow" the version of avr-gcc (and if you like, also avrdude) installed by the Arduino IDE.

https://mil.ufl.edu/374/docs/Install_Atmel_Studio_7.0.pdf :
Note for Mac and Linux Computer Users
If you have a Mac (i.e., a Macintosh computer from Apple) or if you use Linux, you will need an alternate Windows installation
or you will need to install a Windows virtual machine in order to then install and run Atmel Studio.
We suggest that you install
Boot Camp (free and the best); Parallels (not free) or possibly VMware (not free) may also work. UF offers free copies of
Windows 10 Software.
We do not recommend Virtual Box. Wine is another alternative, but this has not been verified to work.
(Note: My best students use Boot Camp!)

Why not VirtualBox?  Any specific reason?

Atmel Studio is a windows only product.
The only way to run it on linux is in a virtual machine running windows.

See http://www.atmel.com/tools/ATMELAVRTOOLCHAINFORLINUX.aspx

De toolchain maar niet de studio. De toochain is puur commandline terwijl de studio eigenlijk microsoft visual studio is met een plugin.


text:
How do I avoid this error trying to connect arduino to pc with linux fedora 20
I used Arduino successfully on my old Linux Fedora 12 system. Now I have a brand new PC with Fedora 20, and have today installed Arduino on it. In my first attempt to use it I typed Arduino as follows at the root prompt, after the "yum install arduino" gave me "Complete!", as follows:
Complete!
[1344][root@localhost:/home/Harry]# arduino
WARNING:  RXTX Version mismatch
    Jar version = RXTX-2.2
    native lib Version = RXTX-2.2pre2

Subsequently I have loaded the "Blink" sketch, and that is running nicely, whether I start the IDE from the command line, which still gives me the same WARNING, or from the desktop icon, which does not give it.
So my question is: please, does this WARNING matter? If so, what should I do about it?

The warning, as I'm sure you can tell, is about a mismatch in version of RXTX arduino is expecting, and what is installed on your system. If everything is functioning, I would not worry about it at all. The versions seem to only be slightly different, maybe just a few bug fixes are missing from the older one.
RXTX is a library for java to communicate with serial devices, but it is not under development anymore and only available from mirrors, not the original developer site. Arduino has moved on to a library called jSSC, which is currently being maintained, and a much better library IMHO. The change to jSSC is still only in the arduino beta version, 1.5.6r2 at time of writing, but it works very well. Anyway, if RXTX ever actually gives you trouble, you can download the beta version of arduino and not have to deal with it.

An excellent answer, covers it nicely for me, thanks.


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.

For reference: answers here recommend that a filter inductor should be added after PWM, to make it effectively a buck converter, which actually lowers the voltage. This way you can eliminate the need of a resistor. More details on buck converter design here.

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.


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:
Read data from 3 ColorPal 28380 simultaneously on Uno/Mega
I've been trying to get an Arduino (I have a Mega and Uno lying around) to read values from a small array of 3 ColorPal 20380, which individually, work as intended with some reflective material. The demo gives no problem, but I am confused as to how to approach activating all the 3 sensors and reading the 3 different sets of values so that I can analyze them in a program on the Arduino.
How can I get all three sensors to output data to my program in parallel? I want to use the values at the same point in time on all three sensors to do some calculations in my program. Should I approach something like a state machine? Or at least near-parallel (a few ms delay is fine too)? How would an example look like?
The most confusing thing for me is the non-inverted, open-drain protocol it uses. From the documentation:

Because of the open-drain protocol, the pin used to communicate with the ColorPAL should always be configured as an input, except when being driven low. Also, when starting up, you should wait for this pin to be pulled high by the ColorPAL before trying to send it any commands.

I tried modifying the demo to something silly in sequence like this just to see how it would work in the Arduino but I got nothing (pins 2, 4 and 6 are the data pins):
/* ColorPal Sensor Example for Arduino
  Author: Martin Heermance, with some assistance from Gordon McComb
  This program drives the Parallax ColorPAL color sensor and provides
  serial RGB data in a format compatible with the PC-hosted
  TCS230_ColorPAL_match.exe color matching program.
*/

#include <SoftwareSerial.h>

int sio = 0;
const int unused = 255;         // Non-existant pin # for SoftwareSerial
const int sioBaud = 4800;
const int waitDelay = 10;

// Received RGB values from ColorPAL
int red;
int grn;
int blu;

// Set up two software serials on the same pin.
SoftwareSerial serin = SoftwareSerial(sio, unused);
SoftwareSerial serout = SoftwareSerial(unused, sio);

void setup() {

  // Unoptimized setup

      sio = 2;
      serin = SoftwareSerial(2, unused);
      serout = SoftwareSerial(unused, 2);
      Serial.begin(9600);
      reset();                // Send reset to ColorPal
      serout.begin(sioBaud);
      pinMode(2, OUTPUT);
      serout.print("= (00 $ m) !");       // Loop print values, see ColorPAL documentation
      serout.end();           // Discontinue serial port for transmitting

      serin.begin(sioBaud);           // Set up serial port for receiving
      pinMode(2, INPUT);

      sio = 4;
      serin = SoftwareSerial(4, unused);
      serout = SoftwareSerial(unused, 4);
      Serial.begin(9600);
      reset();
      serout.begin(sioBaud);
      pinMode(4, OUTPUT);
      serout.print("= (00 $ m) !");
      serout.end();

      serin.begin(sioBaud);
      pinMode(4, INPUT);

      sio = 6;
      serin = SoftwareSerial(6, unused);
      serout = SoftwareSerial(unused, 6);
      Serial.begin(9600);
      reset();
      serout.begin(sioBaud);
      pinMode(6, OUTPUT);
      serout.print("= (00 $ m) !");
      serout.end();

      serin.begin(sioBaud);
      pinMode(6, INPUT);
}

void loop() {

  sio = 2;
  serin = SoftwareSerial(sio, unused);
  serout = SoftwareSerial(unused, sio);
  readData();

  sio = sio + 2;
  serin = SoftwareSerial(sio, unused);
  serout = SoftwareSerial(unused, sio);
  readData();

  sio = sio + 2;
  serin = SoftwareSerial(sio, unused);
  serout = SoftwareSerial(unused, sio);
  readData();
}

// Reset ColorPAL; see ColorPAL documentation for sequence
void reset() {
  delay(200);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  pinMode(sio, INPUT);
  while (digitalRead(sio) != HIGH);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  delay(80);
  pinMode(sio, INPUT);
  delay(waitDelay);
}

void readData() {
  char buffer[32];

  if (serin.available() > 0) {
    // Wait for a $ character, then read three 3 digit hex numbers
    buffer[0] = serin.read();
    if (buffer[0] == '$') {
      for(int i = 0; i < 9; i++) {
        while (serin.available() == 0);     // Wait for next input character
        buffer[i] = serin.read();
        if (buffer[i] == '$')               // Return early if $ character encountered
          return;
      }
      parseAndPrint(buffer);
      delay(10);
    }
  }
}

// Parse the hex data into integers
void parseAndPrint(char * data) {
  sscanf (data, "%3x%3x%3x", &red, &grn, &blu);
  char buffer[32];
  sprintf(buffer, "R%4.4d G%4.4d B%4.4d", red, grn, blu);
  Serial.println(buffer);
}

I don't think you can reinitiate SoftwareSerial several times. Try using variable like e.g. serin1, serin2, serin3 and serout1, serout2, serout3 and (only) initiate them before setup() to make it easier, try getting only one to work first. Then later add the other two.

So looking around the SoftwareSerial library, it is impossible: "It is possible to receive on two different SoftwareSerial ports in the same sketch. You just have to take some care that you aren’t trying to receive from both simultaneously. There are many successful designs which, say, monitor a serial GPS device for a while, then later accept input from an XBee. The key is to alternate slowly between them, switching to a second device only when a transmission from the first is complete." Source

I will try to learn how to use the AltSoftSerial (Apparently this instead for the Uno) since the author says that it can work in parallel instead, but disables a few pins.

You could try using 2 pins, instead of one. One for the RX and the other (via a transistor) for the TX. You'd have to filter out the TX data also coming into the RX pin.

@Gerben Could you explain to me how and what hardware I'd need to wire it using two pins? I have very limited electronics experience, to be honest. Most of this project is a learning experience.

Like I said, just a simple transistor. TX pin on the arduino, via a (±1k) resistor, to the base of a regular transistor; emitter to ground, connector to the shared TX/RX line; connect the RX pin to this same line. Though I'm not entirely sure if it works. I too am still a bit new to this.

I'm also having issues in reading color from 2 colorPal sensors with Arduino. Could you please update if you made any progress?

Try using serin.listen() for each SoftwareSerial before using serin.read().
Only one pin can be read at a time and by default it's reading from the last pin initialized.

I'm doing something similar with you right now. I'm troubleshooting this right now so we can collaborate.
First of all, even though you have setup 3 pins, you're only telling the Arduino to read only 1 sensor because they're using the same variable (pin6 since it's the last one you set up). You have to declare each pin with a different variable then create 2 more readData() functions to read each pin as a start. But even after I set it up with that, it only read one colorpal. Reading up a little more on the Uno board, it seems that only pin 2 and 3 can do serial interrupt which we need to use to communicate with the ColorPal. I'm not 100% sure as I'm a novice still, but from what my analysis and research shows, that's the problem right now. I'll update if I find anything.

I'm also a novice when it comes to electronics, so we're on the same boat. I've delved a little deeper into the comms scheme, and noticed this sensor uses a 1-Wire communication scheme or "the non-inverted, open-drain protocol" mentioned, which seem to use normal GPIO with that OneWire Arduino library. But this demo code uses the SoftwareSerial library instead, which seems to have its own complications, including only receiving one stream of data at a time. The Setup part is a fair point though.

That said, the Arduino Uno seems to have only two native UART pins (pin 0 and 1), so it seems that having three or more will have to incur at least using some other sort of pin and a library for the communication scheme. I'm looking into the aformentioned OneWire for Arduino and see if I can come up with something...


text:
Arduino LCD shows only black boxes
I've hooked up my Arduino on this LCD, and after running the following code, all I see is a row with black boxes and another one empty.
//LiquidCrystal d(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(0, 1, 2, 3, 4, 5);

void setup() {
     lcd.begin(16, 2);
     lcd.print("hello, world!");
}

void loop() {
     lcd.print("hello, world!");
}

Wiring:

(The UTP cable is used just for the data lines :-)
Actual wiring photos: (sorry for the total klutz in the wiring, I had limited solid-core wires so I had to use these scrap ones)

CAT 5 solid core is notorious for making poor connection in a breadboard. Have you tried a continuity check between the output pin of the MCU and the LCD input pin for each? That is, checking it without touching the wire in question.

I think your contrast resistor may be too high. Do you have a 10k pot so you can adjust it? Do you also have a schematic that you're following? Can you post this up

I'l try connecting with non-CAT5e wires and report back

@Samuel I just tried with normal solid-core wires and still nothing, so I believe wire problems are ruled out.

@BigChris I'm afraid i don't actually have breadboard space for a potentiometer ):

The problem was that the R/W pin on the LCD was left floating, after I connected it to GND, I started working :)


text:
Prototyping method
I'm currently using a normal breadbord 'n' solid-core-wires for prototyping, but it gets messy when I need to connect a large number of pins on the arduino, as when using an LCD display + another sensor. What are my other options for prototyping?

The real strength of an Arduino is shields. Ironically, that's also its biggest weakness.

After seeing pictures of shields and shields on top of each other, I really wanted to stay away from stacking things as possible i can

Use a protoshield like: http://arduino.cc/en/Main/ArduinoProtoShield or make your own out of protoboard

One of the Arduino's greatest strengths are shields, and shields upon shields. (Another is it's ease of programming via USB amongst a whole host of others).
They are perfect for prototyping. There's nothing wrong with breadboarding it as well, but it's pretty much one or the other (excluding making your own circuit board).
I am working on a garage controller and it has three shields on top of the arduino itself.

XBee/wireless coms
a relay shield, and
a prototying shield where I have created custom circuitry (buttons, connectors, optocouplers etc).

Especially with the top shield, I have made several changes to get it to perform as I'd like. If I'd committed to making a custom board, then I would have had to change it (and re-change it). What I've done would be virtually impossible on a breadboard.
The idea is, you use the shields to get your idea up and running, as a proof of concept. Then, you could/can leave it as is, or you could take the next step, break it down to the required components and make a custom PCB for your project. If it wasn't for shields and stacking shields, you would either breadboard it (which as you've indicated can get ugly, cumbersome and problematic), or make a PCB which (depending on the project) might not be a small task. So shield it up, test it out, then build your own based on what you've put together.
That's not to say, you have to make your own PCB in the end, many projects can remain a shield on an arduino. So if you can find a shield to do specifically what you're after, then why wouldn't you use it?


text:
Reading speed of different arduinos
I'm thinking about using an Arduino for one of my Projekts. This would require that the Arduino can read/write a digital input/output in the order of 100kHZ to 1MHz. Is this possible or do I have to resort to my own boards using ATmegas?

Depends on what else you want to do besides read/write the digital IO.

How many pins are you changing? Digital or analog? PWM? What other code are you running? You're super vague here, as there are hundreds of different factors that will affect it. Also, some boards have different clock cycles. Can you please edit your question to make it less vague? Thanks!

You really need to provide more information for people to be able to provide anything useful.

Focussing on your final question:

Is this possible or do I have to resort to my own boards using ATmegas?

Remember, an Arduino is already just an ATMega already on a board. Designing your own board around an ATMega that is already part of the Arduino family is not going to significantly alter your project. That is unless you are going to have supplementing hardware, or go via higher clock speeds or ARM processing.

Any Arduino will do just fine. Technically, you could output 8 digital signals simultaneously at the Arduino's clock speed (16 MHz on most models), as it only takes one clock cycle to flip an output bit.
In more realistic scenarios 100kHz is no problem at all, and depending on your code 1MHz is possible as well.

Please note that using Arduino library's digitalRead() and digitalWrite() will take much more than a single clock cycle as these methods do a lot before flipping the right output bit.

It's also worth noting that while you can read an input in one clock cycle, if you want to do anything with the values you read in, you will have to stop reading the inputs.

And that's why I said technically and in more realistic scenarios. Furthermore, my claim that probably any Arduino will be able to do simple digital reading, processing and writing at speeds > 100kHz is true.


text:
Switch 230V 50Hz using a digital out pin
I would like to control normal household appliances like lamps, pumps etc. using my Arduino with up to 5 A. I looked a little around, but it seems, that most relais draw more current than the Arduino is capable of supplying.
How can I switch an 230 V AC current using my Arduino?

My advice would be: don't do it unless you're perfectly aware of the danger. Rather use a dedicated isolated device for that (eg an SSR).

@jfpoilpret relays are also isolated. The only safely advantage of SSR are that they usually have screw terminals instead of just leads.

The good advice to people asking how to drive a relay to control mains voltage is: don't.
Start with a complete solution such as those from PowerswitchTail.com and sold by many places:  Powerswitch Tail
You can get these already built or in kit form.  The 20 $ price is small price compared to damage to people or home you might incur with a home built solution.

Get a logic level n-channel MOSFET that is rated for your relay's voltage and current requirements, and an external DC power supply that's able to put out enough current to drive the relay. Feed the power supply into the relay coil. Connect the ground of the coil to the drain of the MOSFET. Connect the source of the MOSFET to ground. Connect the MOSFET gate to your Arduino control pin.
You might be able to find a relay that will run on 5V at low enough current that you can drive it with a MOSFET and the 5V out from your Arduino, but make sure you don't exceed the total current limit of your Arduino's regulator.
Make sure you put a flyback protection diode in parallel with your relay coil, pointing to block the normal flow of current through the coil, so you don't fry your transistor.
Alternatively you can buy solid state relays that can switch large AC loads using logic level signals, but they're expensive.

A regular transistor instead of a MOSFET should be fine too. Relay coils don't use that much current.

True. The Transistor should be run in saturation. However, with a BJT transistor it's harder to pick the right transistor and run it in saturation. Logic MOSFETs have VERY low gate current, and very low drain-to-source resistance.


text:
Why voltage at AREF is given by Vin * R2 / Rtotal
In chapter 4 of Arduino Workshop on page 85 (or page 31 in the pdf) it says that the voltage at AREF in the schematic is given by:
Vin * R2 / (R2 + R1)
However, the voltage is flowing from 5V to Ground so isn't AREF actually in parallel with R1, and so shouldn't AREF be given by:
Vin * R1 / (R1 + R2) ?

You are correct.
$$V_{ref} = \dfrac{R_1}{R_1 + R_2} \cdot V_{CC}$$
or Vref = Vin * R1 / (R1 + R2) until we finally get MathJax enabled on this site.


text:
Arduino IDE / Teensy 3 on Ipad
Does anyone know a good IDE for Ipad to write Arduino code and compile it for teensy 3 ?
Answers with different alternatives would be appreciated

I don't know of any way to compile it on an iPad, but Textastic should do the trick for writing the code if you set the syntax highlighting to C++.


text:
Power converting - up or down?
Sorry if there is an obvious answer to this - I'm pretty new at Arduino and electronics. I've searched a bunch, but I think I'm too vague - and don't know what terms to look for.
I have a pretty simple project using a 3.3v Arduino Pro Mini (https://www.adafruit.com/products/2377) and a 12v button/LED (https://www.adafruit.com/products/1185).
I'd like to give the LED the full 12v so the light is a bright as possible. The system will be battery operated.
The question is: Do I need a 12v power supply or can I use a 3.7v power supply and upgrade it somehow? I know I can power the LED with 3.7v but then it's really dim. Is there a way to "upgrade" the 3.7v to 12v? I would assume this would draw more power and drain the battery faster, but I think that would be ok.
I'm hoping to get away with a 3.7v power supply because I want to use a lithium ion polymer battery (https://www.adafruit.com/products/328) - since it's small and rechargeable.
Seems like if I go with 12v source then I need a much bigger battery pack, and I'm hoping to keep the project small. Not sure if it would help to know, but I only need the device to run for 4+ hours between charges.
I'm guessing people will say to go with 12v since the Pro Mini can downgrade the 12v supply so there'd be less parts I have to deal with (I can already make this work). But, again, I was hoping to get away with a small rechargeable power supply. Or, are there good, small 12v batteries - I can't seem to find any on Adafruit or SparkFun.
Any recommendations? Thanks!

The product description states "The LED has a built in resistor so you can run it up to 12V"., But, of couse, at 3.7 you won't get enough bright. I'd probably feed the Arduino with a 12 vdc power source and divert some of the power for the button. Maybe you need to find a lower voltage button, or test the one you have with the 3.7 v supply,

Since your project is to be battery powered, you want to make your system as efficient as is reasonable.
So I am going to take an approach that ends up improving the efficiency of your project.
The button you describe in your link states :

This button has a domed red plastic cover with a black retaining ring around it. There's an optional LED included

Further, the LED included has a "built in resistor", so that the LED can operate from 12 volts.
Since you would have to install the "optional LED",  why not purchase a Red LED that operates from lower voltage. You will still need a resistor but you won't need to have a voltage converter.
Example  :  Their LED probably has a 2 volt LED (approximate) that operates at perhaps 20 mA).  This would require a 500 ohm resistor (which they incorporate into the LED).  The power loss (wasted) in the resistor is 0.2 watts (200 mW).
Improved Example :  With LED of about 2 volts operating from 3.3 volt power source.  This would require a 68 ohm resistor.  The power loss in the resistor would be 0.027 watts (27 mW).  A substantial improvement in efficiency.
The manufacturer of the button does not give specifications for the LED (the one with the resistor included).  You should connect their LED to a 12 volt power supply and measure the current drawn.  It is possible their LED draws more current than I have shown in the examples.  This would require a re-calculation of the resistor values.
But in any case, the improvement in efficiency will still exist.

Thanks! Would a 2v LED be way dimmer than the 12v one? I don't know a lot of about electronics (clearly), but I guess I assumed the higher the volts the brighter it would be? For my project a nice bright LED is desirable.

I reread your comment... Realized I missed your point. Yeah, if the LED is only 2v then your solution would be perfect! I'll try to find the specs on the LED... That being said, am I still going to be limited on my light output based on 3.3v? I think I'll have to do some tests... Thanks for your response!

I'm thinking this is what I'll need: https://www.adafruit.com/products/754 Thanks again for the suggestion!

Would a 2v LED be way dimmer than the 12v one? - LEDs have a standard voltage drop (around 2V depending on the colour). When you get a "12V LED" it just has a bigger resistor, as Marla said. See Wikipedia for a bit more detail.

The ones you linked from Adafruit have a slightly higher voltage drop: "3.0V Typical Forward Voltage, at 20mA current". You still need the current-limiting resistor though.

Basically you have two choices. There is a third, but you don't wan to take that route.
The third route is to directly power the system with 12V and rely on the Arduino's regulator to drop it to the right voltage for the Arduino. That is very very inefficient and wasteful, and your battery won't last very long - plus the regulator will get hot. So don't even consider that option.
So the two sensible options - start with 3.7V and step it up to 12V using a boost regulator, or start at 12V and step it down using a buck regulator.
Which of those will be the easiest and most efficient?  Well, there's not much to choose between them.
With either of those solutions you are converting voltage and current. With a buck regulator you are converting voltage into current, and with a boost regulator you are converting current into voltage.
If you start at 12V and step it down yes you need more cells, but each cell can be smaller since each one will have to supply less current.  With 3.7V and stepping up you will have just one cell, but it will need to be bigger since it will have to supply more current.
From a charging perspective it is easier to charge a single cell since you don't have to worry about cell balancing.
From a price and availability point of view, buck (step-down) regulators are cheaper and easier to get hold of on places like eBay than boost (step-up) regulators as pre-built circuits.
So really the choice is yours - 12V (well, 11.4V it would really be - 3S LiIon / Li-Poly) and buck regulator, or 3.7V and boost regulator. Both will work, both will be about as efficient as each other.
Incidentally there are boost regulators specifically designed for driving LEDs from battery sources - you might like to look around to see what is available in that way.

Thank you for your reply! I think I will dig into your suggestions a bit - since I think the brightness of my LED may require more power. For now, however, I think Marla's answer above my be better for my project.


text:
Buffering data from EthernetServer clients
I was trying to write a Telnet server that would be able to accept commands of sorts using the Arduino Ethernet library, and in order to access what the client was saying (to compare it to strings to check what command the client entered), I made a buffer string that would read until \n, which is part of the standard Telnet library. However, the string would never get printed to the serial connection (just for debugging purposes). Here's my code:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xFE, 0xED };  // this client's MAC address

EthernetServer server(23);  // telnet is 23
boolean alreadyConnected = false;

void setup() {

  Ethernet.begin(mac);

  server.begin();  // open the socket

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial to start, Leonardo only
  }

  Serial.print("Connect to ");
  Serial.print(Ethernet.localIP());
  Serial.println(":23.");

}

void loop() {

  EthernetClient c = server.available();

  if (c) {
    String messageBuffer = "";

    if (!alreadyConnected) {
      c.flush();
      Serial.println("New client");
      c.println("test post, please ignore");
      alreadyConnected = true;
    }
    if (c.available() > 0) {

      char thisChar = c.read();

      //server.write(thisChar);

      //buffer until the client sends a new line
      if (thisChar == '\n') {
        Serial.println(messageBuffer);
        messageBuffer = "";
      } else {
        messageBuffer += thisChar;
      }
    }
  }
}

Most of this code was copied from the Telnet chat server example, but I changed the Serial.write(thisChar) line, because I wanted to put it into a string first. When this is run, and a user telnets to the IP, the Arduino prints New client, but when the user sends data, it doesn't print anything.
Any suggestions for what I'm doing wrong?

That is the complete code. As I've said, I fixed the problem.

Well, I asked on the #arduino IRC channel, and realized my stupid mistake. I was setting the buffer to "" inside the loop.


text:
Which Arduino is compatible for atmega164pa
I am working on a project using 5 pins of ADC, 5 pins for PWM, and LCD. I need to use Atmega164pa. I would like to know how I can transfer it to Arduino. Is there any Arduino compatible with this chip?

Why exactly do you need to use the 164PA?

@microtherion the reason is that ATMEGA16 does support at most 4 PWM channels while I need 5 PWM channels.

My question was meant to be more along the lines of why it would be an 164PA rather than a 644PA or 1284PA; for the latter, there used to be the Sanguino board, though it's not clear whether these still are produced.

There is an Arduino core for the '1284A, but it can be adapted to the '164A.

but the link is to the software not to the board. What is the name of board that I can buy for this software.

You don't need a board for it; the DIL package mounts on a breadboard.

sorry but what is DIL package?

http://en.wikipedia.org/wiki/Dual_in-line_package


text:
analogRead-ing Potentiometer Values in void setup()
I've run into a problem while coding a speedometer meant for bicycles. The speedometer would require the diameter of the wheel in inches for maximum accuracy, so I'd like to have an adjustable (by potentiometer) numerical prompt appear on two 7 segment LEDs. So, for example, the device would be turned on, it would display "16," the user would turn the potentiometer knob until the 7 segment LED displays "24," then the user would push a button [indicating the beginning of the loop()], and the speedometer would begin measuring and displaying his or her speed.
This would be an easier task to accomplish in the loop section of the code, but, because I only want this series of potentiometer analogReads to occur once, it gets a bit trickier.
Some clarification: Every other component of the speedometer works (such as the 7 segment LEDs via shift register and the actual measurements), so I'm only looking for help with the code for the potentiometer.
Thanks!

You presumably know that:  The easiest and usual way to read a potentiometer is to connect the "track" between V_pot (often = Vcc) and ground and to connect the pot "wiper" to an analog input pin. You then use analogRead(Ax) to read the pot value in the range 0-255.
The use of analogRead() is valid in setup.
However a more "real" method would be to have a "flag" variable that indicates that the speedo initialisation code has or hasn't been run.
Set this flag to false in setup, detect and action it in loop and then set the flag to true so that the code is not repeatedly actioned.

eg
void setup()
{
...
boolean initialised = false ;
...
}
void loop()
{
if (initialised == false) {
// initialise speedo
//  ....
   initialised = true;
}
...
} // end of loop()
}

If you really want to use this feature in the setup() then you can do like this:
#define BUTTON 2
boolean not_done = true;

void stopDiameterSetup() {
    // some button debounche code
    ...
    // we are done with setting up the diameter.
    not_done = false;
}
void setup() {
    ...

    // POT reading
    interrupts();
    attachInterrupt();
    while(not_done) {
       attachInterrupt(BUTTON, stopDiameterSetup, CHANGE);
    }
}
void loop(){
// your loop code
}

If you can't or afraid to use interrupts then just check for a button pressed inside the while loop.


text:
Using A 4 Ohm Speaker With Arduino
I've salvaged a 4 Ohm, 1.5 Watt speaker from an old computer, and I was wondering how I'd go about getting it to work with my Arduino. I've heard of various amplifier circuits such as opamps, but I do not know which would be the best for my situation. I've also heard that using the speaker in certain ways (such as directly connected to a pin from the Arduino) could damage both the speaker and the output pin, so that is definitely something I'd like to avoid. I'm not looking for anything complicated; I'm just trying to get a feel for the general circuitry, programming, and speaker volume. Any suggestions?

5v, 4ohm, >1amp from a pin rated for 0.04amps; this isn't safe!
You would need a driver, but it would suffice to add a small transistor & a couple of resistors to drive it; here is a slightly more complex layout, there are many examples on the web.