text:
Arduino Shield Pin Conflict
I have a Freetronics Etherten and am trying to use the NFC Shield - both the board and shield are trying to use Pins D10,D11,D12,D13
So my question - Is there an elegant way to have these two work together.  This really applies to any combination of shield with conflicting pins.  I'm thinking maybe use some in between headers or M/F jumper wires?
Is there a neat way to do it?

I blather on about something similar here: http://arduino.stackexchange.com/questions/3892/motor-shield-and-wireless-transceiver-compete-for-same-pins/3895#3895

You need this: https://www.sparkfun.com/products/11002
"The Go-Between Shield “goes between” two shields that aren’t compatible and effectively reassigns the pins. This trickery is achieved by isolating the top and bottom sides of the shield with surface mount headers and breaking them out into tables of jumpers that can be bridged to divert signals to and from different pins."

D11-D13 are the SPI pins. So you should only move D10 (SS) to another pin.


text:
how to use strstr() in serial communication?
I have a SIM900 module and Arduino, both are working fine. In my previous programs I have use strstr() command to find specific word from a string but they were constants and pre defined in the program but now I want to read serial communication from SIM900 and detect a specific word from it. But it is showing me

invalid conversion from 'char' to 'const char'

This is my program:
int x;
char sms;
char response;
char disp;
void setup()
{
  Serial.begin(2400);
}

void loop() {
  while(Serial.available() == 0);

  if(Serial.available() > 0)
  {
    sms = Serial.read();

    disp = sms;
    if (strstr(disp,"track")) //Comparing word entered with word stored in program
    {
      Serial.println("Found the  word!");
    }
  }
}

There are two problems.
1) you are trying to have the Arduino's single UART talk to both the SIM900 and the PC.
2) disp needs to be an array of char's, as to compare for words phrases.
Try the following. It implements a 2nd Soft serial port to which you can connect the SIM900. Along with building an array char at a time.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

char buffer[16];
#define buffer_size sizeof(buffer)/sizeof(buffer[0])
int8_t buffer_pos = 0;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Serial to mySerial demo started");

  buffer_pos = 0;
}

void loop() {
  char inByte;
  while (mySerial.available()) {
    inByte = mySerial.read();
    while (buffer_pos >= buffer_size) {
      for (int8_t i = 0; i < buffer_size - 1; i++) { // if shift buff left if at end of buff
        buffer[i] = buffer[i + 1];
      }
      buffer_pos--;
    }
    buffer[buffer_pos++] = inByte;
    if (strcasestr(buffer, "track")) {
      buffer_pos = 0;
      Serial.println("TRACK FOUND!");
    } else {
      Serial.write(inByte);
    }
  }
}

mpflaga thanks for taking your time to help me but your solution didn't work,It's showing up "TRACK FOUND!" for anything I send(to whatever word I send),I tried to change "strcmp" to "strstr" but in this method it's not reading string completely to the end.it's showing unfinished data.I took the screenshots.http://s29.postimg.org/i0mrhzw13/image.png.I will also add code that I modified.

My modified code:http://freetexthost.com/mwez052ng4, My requirment is very simple ,I send sms to sim900 a specific code and arduino should receive this and search for that key word,If it finds that keyword it needs to print predefined text.

did you try "strcasestr" I see your picture is upper case

yes,I did still no use :(

I don't know what's wrong with above program,but I have made another program:here: http://freetexthost.com/rw6cdpf3m3 , Here is the output : http://s18.postimg.org/amcjzqfu1/Untitled.png, it basically reads serial data from sim900, I just need code to detect specific word from that text,for eg: "145" in that incoming data, since it is serial data not a const char,please help me

I have corrected my above code. There was a minor bug, missed buffer_pos--; in the rotate buffer left. Also changed to strcasestr. I don't have a SIM900 to test against, rather I validated against a more simpler code. It worked as expected. See GISTHUB strstrSerial.ino

source: Stack Exchange

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

sort: votes


text:
Code does not pass `gsmAccess.begin(PINNUMBER)==GSM_READY)`
I am not able to get my code to pass

if(gsmAccess.begin(PINNUMBER)==GSM_READY) {

I have modified the PIN number on my sim card to be 0000, and yet its stuck on begin.
How do I prepare the SIM CARD to pass the begin

This has been abandoned for months without information sufficient to make it answerable ever being provided.  Voting to close as unclear.

Closing needs a better reason, not a vendetta.

That your problem is insufficiently specified is a valid reason.  Otherwise, edit your question to make it answerable.  Post the code of the method where it gets stuck, and add logging to determine where exactly that happens.

This would be an acceptable question if it had a bare minimum sketch (enough code that we could run it on our own Arduinos and reproduce the issue). Feel free to edit. Thanks!

Try putting the SIM card into a mobile phone in case it hasn't been initialised by your provider. Set up the PIN for the card using the settings on the phone, see the manual for instructions on how to do this.
Now you can use the PIN you entered on the phone to unlock the SIM in your code.

Tried it, did not work.

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


text:
Mega2560 R3 pin functions
When I read about mega2560 I saw it has 54 digital that can be used as input or output.
later on I saw the some of them are used for things like communication.
So I would like to know if the communication pin can still be used as output ? (to power leds)

Yes. Any pin can be used as a digital input/output. However, you cannot use certain communications when using those pins.
The types of communication and their effects on the pins:

SPI: This protocol is used for certain communications with certain breakout boards and shields. For example, the ethernet shield uses SPI to connect. On the Mega(2560), it is pins 50-53.
I2C: This protocol is also for connecting to external items. It is much slower than SPI, but uses only two pins. On the Mega, it uses pins 20/21.
UART/Serial: UART is a communication method that uses two wires and transmits bytes of data. It is often used to connect to things that don't need extreme amounts of data passed, but need a stable two way connection.

On all standard boards, the main UART is on pins 0 and 1. This is usually connected to a UART to USB chip which is sent to the computer. Note: you should still be able to upload sketches if they act as an output and random on/off won't hurt the device.
The Mega(2560) also has UART on pins 14/15, 16/17, and 18/19.

Yes, you can.
You are referring to SPI, I2C, and the 4 serial interfaces. If you want to use those you have to use the predefined pins for that. If you are not using those you can use them as normal GPIO.
If you want Serial communication for debugging, you shouldn't use digital pins 0 and 1.
If you need even more pins, you can even use the analog pins and digital input/output pins.


text:
Slice string at “:”
I need to slice a string (eg- 4:288:18464:288:4) at ":" into an array({4, 288, 18464, 288, 4}) I used the following code, but its giving only '4' in the serial monitor when "4:288:18464:288:4," is given to arduino.
void displayString(char* s)
{
  char* text = strtok(s,":");

  while(text != NULL){
  text = strtok(NULL,":");}
}

void loop()
{
  if(Serial.available() > 0)
    {
        str = Serial.readStringUntil(',');
        str.toCharArray(text,99);
    }
  displayString(text);
Serial.println(text);
}

Do you know in advance how many substrings you expect from the original one?

Every string will contain 5 substring. But the number of strings will be different each time.

You don't use strtok the way it should:
char* text = strtok(s,":");
while(text != NULL){
    text = strtok(NULL,":");
}

Your code just replaces, in s, all occurrences of : with 0 (i.e. a byte of value 0, not the ASCII value of '0'), thus terminating each substring.
At the end of displayString(text) call from loop(), text still points to the 1st character of the original string (in your post 4:288:18464:288:4), but that string now terminates at the position of the first :, which explains why Serial.println(text) prints just 4.
Now if you want to split the original string into an array of substrings, as asked in your question, you need to modify displayString this way:
// Maximum number of substrings expected
const int MAX_SUBSTRINGS = 5;
// Array of pointers to each substring after displayString() has been called
static char* substrings[MAX_SUBSTRINGS];

void displayString(char* s) {
    // First clear the array of substrings
    for (int i = 0; i < MAX_SUBSTRINGS; i++)
        substrings[i] = 0;
    // Now split the input string
    char* text = strtok(s,":");
    int i = 0;
    while (text != 0 && i < MAX_SUBSTRINGS) {
        // A toekn was found: append it to the array of substrings
        substrings[i++] = text;
        text = strtok(0,":");
    }
}

After calling displayString(text), you can use its result in loop() as follows:
void loop()
{
    if (Serial.available() > 0)
    {
        str = Serial.readStringUntil(',');
        str.toCharArray(text,99);
    }
    displayString(text);
    for (int i = 0; i < MAX_SUBSTRINGS; i++) {
        if (substrings[i] != 0)
            Serial.println(substrings[i]);
    }
}

Note that this will work ONLY if the original string contains no more than 5 substrings delimited by :. If the max number of substrings cannot be known at compile time, then you'll have to use dynamic allocation, which is generally not a very good idea on embedded platforms.


text:
Galileo - servo motor moves only in one direction and it doesn't turn back
I have an Intel Galileo (1st gen) and a servo motor (Tower Pro SG90).
My problem: my servo moves only in one direction and it doesn't turn back.
I want to perform a movement from 0° to 90° and then from 90° to 0° again.
At the moment, I have just tried the official arduino snippet for servo motor that should perform a similar movement. But, as said before, the servo doesn't turn back.
Here the code
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Obviously I have made the attachments like on arduino tutorial.
Every help will be greatly appreciated! :)
Thanks in advance

How are you testing this? Do you manually push the servo back to the 0° position? What happens if you swap the 2 for loops? Or increase the delay to something like delay(300)? Very odd problem you have there.


text:
Can I power an Arduino with a computer's motherboard?
I was thinking of using my Arduino to turn on and off a computer remotely. I would like to know if the 5v header pin on a computer's motherboard (which I’m using instead of a USB because the 5v pin provides a constant power supply) can power an Arduino UNO without frying it. If the Arduino can be powered where would the cable from the 5v motherboard pin go into the Arduino?

↑ These are the pins I would like to use

Can you post a picture or a description of this pin? Is it just on a USB header?

There is 5V at the power-header-pins, but I would assume there is a current limiting resistor somewhere on the MB. Better options are using either the internal usb-headers (which have fuses for extra protection). Or use one of the molex connectors used for powering CD-rom drives etc. (Red is 5V, black is GND).

You want to tap off of the +5VSB pin of the ATX or BTX power supply connector and send it to the 5V pin on the Arduino. Where this will directly drive the VCC(5V) of the UNO.

Note that 5V of the USB basically drives the VCC directly, except through a MOSFET that acts as a blocking diode to prevent local VCC from flowing back to the 5V_USB.

Not sure if you are suggesting that the 5V USB is frying Arduino's. If so that is bad. If true; Fix that first.

That said (with good 5V usb) you should be able to find or configure (BIOS) so that a USB connector will remain powered, and allow a wake up from mouse movement. Hence a possible solution would be to use a Leonardo/Micro's Mouse emulation to do just that as to wake the PC, without any hardware mod's.
Freeduino Micro's are pretty cheap.

Applying power to the 5v header, will bypass the polyfuse. I personally would just cut up a USB cable and use the power and ground wires to connect to the PC's power.

I ended up using the cut up USB header method that Gerben said to power the arduino for anyone who wanted to know

As stated by @mpflaga you can power your Arduino by the 5v power rail. As @ Gerben mentions in a comment, doing this will bypass the polyfuse. Because of this, I create my own Arduino for less than $10 (US) with a power regulator. Using a  L7805ACP will regulate the power.
Part List:
• 1 x P-DIP ATMEGA328P-PU programmed with Duemilanove Bootloader
• 3 x Through-Hole 22pF Capacitors (2 for crystal and 1 for Analog power smoothing)
• 1 x Through-Hole HC-49S 16 MHz Crystal (for clock)
• 1 x 5 Volt regulator (peak current 2 A, nominal )(L7805ACP
  Input Voltage = 7.5 to 18 V
  Output Voltage Low 4.8 Volts Nominal 5 Volts  High 5.2 Volts)
• 1 x 22 uF Capacitor (to stabilize power rail during rapid current draw.


text:
Why does an Arduino UNO need two GND ports?
I have really bad eyesight, so whenever I plug in the power wire and the GND wire I always double check if I'm actually plugging in to the power port not one of the two GND ports.
Why does an Arduino UNO have two GND ports, and for what application would one use both of them?

There is actually a third one next to pin 13 on my Uno. It's just convenience to have multiple ground headers. That way you even do without a breadboard for very simple projects.

In electronics circuits, a major point in connecting two circuits and make them "talk" together is to ensure, at the minimum, that they have a common reference of voltage (typically called GND and defined as 0V voltage).
On Arduino, GND pins can be used in 2 situations:

to directly power the Arduino with an external supply which cannot be plugged to USB or power jack. In this case, the positive voltage of that external power source shall also be supplied to Vin pin.
to connect Arduino GND to your circuits.

Having 2 distinct GND pins is, I think, just a matter of convenience when you want to build prototypes but don't necessarily have a breadboard (if you use a breadboard, you will just need to connect its power rail to Arduino GND pin and use this power rail directly).

If you are not using a shield and are directly adding components to the arduino it is nice to have 2 ground so you can attach several components without having to add a bread board.
To be precise, you have 3 ground, since the third is sitting on the left hand side of the board (looking in to the USB port)


text:
AT+CSTT throws an error
I am getting an error on
AT+CSTT="TATA.DOCOMO.INTERNET","",""

What am I missing here?
Code
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
  delay(3000);
  Serial.println("AT+CGATT=1");
  delay(500);
  Serial.println("AT+CGDCONT=1,\"IP\",\"TATA.DOCOMO.INTERNET\"");
  delay(500);
  Serial.println("AT+CDNSCFG=\"4.4.4.4\",\"8.8.8.8\"");
  delay(1000);
  Serial.println("AT+CSTT=\"TATA.DOCOMO.INTERNET\",\"\",\"\"");
  delay(2000);
  Serial.println("AT+CIICR");
  delay(5000);
  Serial.println("AT+CIFSR");
  delay(500);
  Serial.println("AT+CIPSTATUS");
  delay(500);
  Serial.println("AT+CDNSORIP=1");
  delay(500);
  Serial.println("AT+CIPSTART=\"TCP\",\"www.google.com\",\"80\"");
  delay(500);
  Serial.println("AT+CIPSEND");
  delay(500);
  Serial.println("AT");
}

void loop() {
  // run over and over
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Result
AT+CGATT=1

OK
AT+CGDCONT=1,"IP","TATA.DOCOMO.INTERNET"

OK
AT+CDNSCFG="4.4.4.4","8.8.8.8"

OK
AT+CSTT="TATA.DOCOMO.INTERNET","",""

ERROR
AT+CIICR

ERROR
AT+CIFSR

ERROR
AT+CIPSTATUS

OK

STATE: IP IND
AT+CDNSORIP=1

OK
AT+CIPSTART="TCP","www.google.com","80"

ERROR
AT+CIPSEND

ERROR
AT

OK

Edit
SoftwareSerial mySerial(10, 11); // RX, TX

Could you please explain what is mySerial and what circuit it is connected to? Just a part of the code will not provide enough information to analyse your problem.

For others who reach here by search results
Before this applying AT+CSTT command check if the modem is attached to GPRS using the AT+CGATT=? command. If the result is +CGATT: 0 this means the modem is not attached so attach the modem using AT+CGATT=1 command.
This will solve the issue as it was in my case. Even applying AT+CIPCLOSE=0 and AT+CIPSHUT didn't help until I checked that that the result of AT+CGATT=? was returning +CGATT: 0 and applied AT+CGATT=1.

AT+CGATT? , not AT+CGATT=?

Sorry for late Siddharth,
try to get response of only at+cstt=?
Its return a exec  syntax and by following it you can make your frame of at+cstt
some below point may it will help

//TCP connection profile AT+CSTT?
+CSTT: "CMNET","",""
OK APN->"CMNET"
USER->""
PASSWORD->""

and

AT+CSTT="CMNET"
OK
at+cstt=?
+CSTT: "APN","USER","PWD"
OK

It may help you
regards

Have gone past that project long back. Will report back after I try. Thanks for your input.

Try AT+CSTT="TATA.DOCOMO.INTERNET"

tried, did not work\

What does at+cstt=? return?

Just a ERROR, as mentioned in the question above.

I mean what does the exact line AT+CSTT=? return? Also, what does AT+CSTT? return?

Sorry, AT+CSTT="TATA.DOCOMO.INTERNET","",""

Ummm, what is the response to AT+CGDCONT? and AT+CGACT?. Could try adding AT+CGACT=1,1 after AT+CGDCONT=...

In most cases the problem is in low balance and account settings.
As I see, you doing all right.
AT+CGATT=1
AT+CSTT="TATA.DOCOMO.INTERNET","",""

Also, check login/password! It's unusual to have blank credential here, in my country.

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


text:
Difference between SoftwareSerial and Serial
From the sample code
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

What is the difference between, why use 2 types of calls to make AT command calls.

SoftwareSerial mySerial (10,11)
  mySerial.begin(10,11)

and

Serial.begin(9600)

Edit, this answers my question in my own words based on @jfpoilpret response.

It is important to initialize both Serial and SoftwareSerial, since SoftwareSerial is used to send the actual commands to the GSM, and Serial is used to view all the commands and their responses on the debug port of the GSM
The pins on the GSM and Arduino are used to connect the the 2, and pass on actual commands. While the RS232 is only used for debugging. We can however connect a RS232 to USB connector so as to connect the GSM to the desktop(or laptop)
The code in the loop is essential to help convert all actual commands to the debugging RS232 port, and the other way around, so as to enable us to use a tool like cutecom (on ubuntu) to pass commands to the GSM serial input pins.

Important Note : When using cutecom ensure that you select CR line end to send commands.

All Atmel MCU, on which Arduino models are based, include special hardware for serial communication; this part of the MCU is called USART (stands for Universal Synchronous/Asynchronous Receiver/Transmitter).
Based on the Arduino model you have, you may have only one (eg on UNO) or more USART (leonardo, mega...) on the board MCU.
Each MCU USART is mapped to specific pins of the board, you cannot change those pins.
On Arduino, if you use the monitor to send debug information to your PC, then one USART is used, this is when you used Serial.
If you need more than one serial communication link (e.g. because you have some devices that communicate through serial) but your Arduino model has only one USART, then you have to use the library SoftwareSerial that "simulates" the job of an USART only by software. Hence it is much less optimized than the hardware USART.
One advantage of SoftwareSerial is that you can map it to any pair of pins you like.
Going to your code sample:
if (mySerial.available())
    Serial.write(mySerial.read());
if (Serial.available())
    mySerial.write(Serial.read());

Obviously here, Serial is used for debugging (sending info to the serial monitor of your PC), whereas mySerial is used to communciate with the GSM device.
So this sketch is used to allow you to type AT commands on the monitor, which will then be forwarded to the GSM device; conversely, any strings returned from the GSM device will be echoed to the serial monitor.

I'm using SIM808 module with Arduino Uno, one thing that I don't understand is when I use TX1 and RX0 of Arduino to communicate to GSM module, I get error on Arduino software during upload process: something like 'avrude ....' . But when I use SoftwareSerial setting tx and rx pins to pin7 and pin8, there's no problem on uploading when pins are connected. One other thing is that when different versions of Arduino is used how do you communicate to GSM device if you don't use SoftwareSerial? I've seen code for other versions of Arduino and SIM908
at which SoftwareSerial lib. is not used at all.

#include <SoftwareSerial.h>

SoftwareSerial GSMSerial(7, 8); //use pins 7 and 8 as RX and TX

void setup() {
   GSMSerial.begin(19200);               // the GPRS/GSM baud rate
   Serial.begin(19200);                 // the GPRS/GSM baud rate
}

void loop() {
    if(Serial.available()) {
       //to send commands received from Serial Monitor to GSM module
       GSMSerial.print((char)Serial.read());
    }
    else  if(GSMSerial.available()) {
       //To print data responded from GSM module to the Serial Monitor.
       Serial.print((char)GSMSerial.read());
    }
}

In the code above inside loop function first if statement is needed to talk to GMS module from Serial Monitor, e.g. when you type AT in the monitor and press enter your command gets sent to the GSM module.
The second if statement else if is to print whatever is received or responded from GSM module e.g. GSM module responds the received command like AT and its result OK after you send command AT to the module.


text:
Why does this button have a connection to ground?
I am testing this basic button example  from the Arduino tutorial page.
This circuit lets power flow to pin 2 when the button is pressed. When the button is not pressed, the power goes through the resistor to ground, but my question is: why would you even need the connection to ground?
Can't you have power flow from 5V to pin2 or just have NO connection at all when the button is not pressed?

Don't think in terms of where the 'power flows' (current), think in terms of voltages. It will make more complicated circuits easier to understand.

When the button is not pressed, the power goes through the resistor to ground

When the button in not pressed its not the 5v pin that is connected to ground but the input pin is connected to ground.
This is to ensure that the input does not float between 0v and 5v.

When not connected to 5v or GND the input pin tends to randomly change from `HIGH` to `LOW`.
To avoid this and quell external interference you just ground the pin.

Ah, I didn't see that the connection is between pin 2 and ground. Those little buttons always confuse me.

That resistor is called a pull-down resistor. It's there to make sure pin 2 read low when the button isn't pressed. If you don't put it there pin 2 is left 'floating', and it could erroneously read a high value. Google it for more info.
If you want to simplify you circuit you could instead use a pull-up resistor, and connect the button to ground instead of 5v. The ATMega chip on the arduino has these pull-up resistors build into the chip itself, so you don't need to add one to the breadboard. Just not that the input values will be reversed. So pin2 will read LOW when the button is pressed, and HIGH when not. To activate the internal pull-up use pinMode(2, INPUT_PULLUP)

In simple words, to avoid undefined state. This type of resistor arrangement is known as Pull Down Resistor. (Pull-Up also exists)


text:
Controlling flexinol with an arduino board?
I am looking to wire up 16 pieces of flexinol (http://www.musclewires.com/MWFlexinol.php)  using an arduino board. Ideally I would like to be able to activate them independently, meaning that they could all be on, off or in any combination in between. My understanding that they would need to draw more current than the board could handle so some type of shield would be necessary?
Any suggestions would be greatly appreciated.

First thing's first, this just seems to be a wire that has special characteristics. If so, we just need to find out the resistance and use Ohm's law.
From the product page, I found this image:

I can tell from that that it has a resistance of 20 ohms and a recommended current of 1 amp. First, let's see how much current it would draw with a 5V supply. I prefer using a Ohm's law triangle, just because I'm a very visual person. So with this math:

5 / 20 = 0.25

That's 250 mA, but an Arduino can only provide 40 mA! Furthermore, it is only 1/4 of the recommended current that the manufacturer specifies.
To get the full current the OEM specifies you'll need a 20 V power supply capable of at least 1A. Even then, you might want to put in a power resistor to limit the current.
Driving this with Arduino: So, we have a few problems here:

It is 20W, which is quite a bit in the Arduino world
We need to control the current/voltage dynamically
You need 16 of them, so we don't want something too costly
You probably can't find something to fit your needs that is one shield.

What comes to mind is a transistor. I'm not skilled with picking them out, but there are a lot of guides online. You'd then want to add a capacitor and a resistor to make some sort of filter and connect it to a PWM pin to send a varied voltage to the transistor, which will vary the amount of power going through it.
Alternatively, you could use a relay. However, that only does ON or OFF. A solid state relay (SSR) would allow you to use PWM on the relay and then you could add a capacitor/resistor combo on the other end of it, but you'd need a pretty large capacitor or a pretty large frequency for the PWM (which you can modify).

"You'd then want to add a capacitor and a resistor to make some sort of filter and connect it to a PWM pin to send a varied voltage to the transistor" - NO.  This is both unnecessary and highly inefficient.  The thermal mass of the wire will average out the PWM quite well, and it is far more efficient to use a transistor (or better FET) switch which is (to the greatest degree possible) only ever all the way on or all the way off, so keep the control signal to the transistor digital and do not average it with a filter which would cause it to spend time in the lossy "somewhat on" region.


text:
I2C RTC returning bad times - sometimes
I have a TinyRTC I2C clock in one of my Arduino projects, and it works most of the time. But occasionally, it will report the time as 165 hours, 85 minutes and 25 seconds (165:85:25) for a couple of seconds, then go back to the correct time.
I think this has got something to do with a fairly complicated I2C bus that I'm running: it has 12 devices connected to it (the clock, an LCD and 10 BlinkM LED programmable lights).
Here's what I've tried to debug, to no avail:

Replaced the RTC and battery
Replaced I2C pullup resistors
Redid the I2C wiring
Checked current draw of my project (.2A) and made sure the power
supply can handle that (it can)
Used 3 different power supplies in case I was getting noise

I think this is something to do with the I2C bus... the clock works fine when nothing much else is happening on the bus, but as soon as there's lots of activity (LEDs being sent messages, or perhaps other things) it starts reporting the time as 165:85:25).
Any idea how I could (a) isolate the cause of this problem; (b) get right to implementing a solution?

http://arduino.cc/en/Reference/WireEndTransmission Did you try the stop parameter and/or check error conditions that are returned? Hard to tell what's wrong without circuit or code.

What code/library did you use? What was the expected time for 165:85:25?

How large are your pull-ups on the bus?

It might be an error code for I2C or it could be a status report from the TINY RTC. So how are you sure that it is responding with the current time?

@jippie - Your link was useful... am going to try slowing down the I2C bus in case there's a problem communicating with so many devices.

@Gerben - www.pjrc.com/teensy/td_libs_DS1307RTC.html

@Lean - 4.7k pullup resistors

@Treesrule14 - The clock works fine for hours at a time... then reports these weird times, which happens when there's other activity on the bus

Did you check you have no devices with conflicting addresses on the bus?

Make sure you have only one set of pull-up resistors.

Such intermittent issue looks to me a hardware signal integrity problem, specifically around the I2C bus RTC chip. Did you experience any problem from any other device on the same I2C bus (e.g. when all the LEDs are on)? If not, then check on the noise level on RTC chip power and GND. Also, the I2C spec has limit on the bus capacitance load as max as 400 pF. When there are too many I2C device loads on the same bus, the bus may become vulnerable to the system noise.
Debug Suggestion: To narrow down if it is I2C load issue, add an I2C bus driver chip between the main Arduino board and your peripheral. For example, P82B96 from TI. See the spec here. http://www.ti.com/lit/ds/symlink/p82b96.pdf


text:
Using a 16 bit ADC chip with arduino
I need to measure voltage between 0-10 volts using my Arduino Due.  I have an ADS7805p chip, which I believe will work, but am not sure how to wire it on my breadboard.  I'm used to just using the chip on the arduino, but that only goes 0-5 volts and I can't loose the resolution by converting.  Can someone, please, point me to or instruct me on how to wire something like this to my arduino?

Why not just halve the voltage?

When you say "using the chip on the arduino", I guess you mean "directly using the analog inputs of arduino", is that correct?

The important question here is: do you absolutely need 16 bits resolution (as offered by ADS7805 ADC) or can you deal with just 10 bits, or even 12 (as supported by Arduino DUE)?

If 10 or 12 bits resolution is OK, then @Ignacio suggestion is probably the best way to follow.

I do need 16 bit resolution.

A 16-bit ADC will give you a 16-bit result, but the least significant bits won't actually be correctly representative of the signal.  You'll get better results if you can take multiple measurements and filter them (average them in the simplest case).

@ChrisStratton This tampering technique works for standard applications, low quality sensors, low quality ADCs. What if the sensor has a great dynamic range?. What if the application captures the high order modes? Removing LSB data and FIR averaging by design is inappropriate.

@hyprfrcb please spend some time studying signal processing theory, as your claims are exactly backwards.  Averaging doesn't decrease level resolution ("removing LSB data") on the contrary, provided you do not truncate your calculation, it actually increases resolution.  If the extra data is meaningful or not depends on if the input and conversion noise has a characteristic suitable for statistically sampling the desired signal.  Often in the real world it does to a useful extent.

"Averaging" from "extra", "statistical", "meaningful" data, only confirms that your sensors are untrustable. With high dynamic range (~120dB), low noise (~0.01% error or less) sensors, you dont need to do that. Never. And again, when interested in high frequency modes, that tampering is the worst design.

@hyprfrcb "tampering" is not a meaningful term of signal processing - that you would persistently insist on mis-using only confirms this is not a familiar subject area for you.  Bandwidth and resolution are indeed extremely distinct subjects.  Very few sensors actually have > 120 dB dynamic range, when they do, they push the limits of ADC technology.  But if you study deeper, you'll discover that noise of the proper character can manage to statistically sample with finer resolution than the ADC.  Keep studying - you still have a lot to learn about everyday practices in this industry!

Well, you are the one who must study indeed. And it is a shame you dont have experience and knowledge in 24 bit ADC DAQs or 120dB dyn range sensors. Good luck averaging your sensors for getting ride of the noise!

The ADS7805 is old but still a pretty good ADC. I could imagine that you just have a few lying around that you want to use. I would simply wire it to two parallel in / serial out chips like the 74HC589 or CD4021 as used in this example:
http://www.arduino.cc/en/Tutorial/ShiftIn
Start the conversion as described in Duncan C's answer and then simply clock in all 16 bits. I think you could then probably get away with 4 or 5 control lines.

If you really need 16 bits of resolution then you could use that chip, but it's going to be a lot of work. Also beware that according to Mouser's website, it is not recommended for new applications. It sounds like it's being phased out/replaced.
Take a look at the data sheet linked from Mouser's website:
ADS7805p datasheet
It has 16 bits of parallel data output, plus what sounds like 2 control lines, CS and R/(not)C (Don't know how to make the proper symbol.)
It sounds like you pull CS and R/C low to trigger a conversion, then wait for not busy to go low, switch R/C to high, then read the 16 bits of data.
To use this chip you're going to need 18 or 19 pins from your Arduino. You might want to consider a chip with a serial interface instead.

I saw that bit about not being recommended for new applications.  I'm looking around now to see if I can find a 0-10v one now.  Thanks for the thought.

The due has plenty of pins, but they are 3.3v and the ADC uses 5v logic.


text:
Can the nRF24L01+ CE and CSN pins be attached to Arduino pins A0 and A1?
This documentation states that the CE and CSN pins can be specified.  Can I specify A0 and A1 as these pins?

Yes, you can. The mirf library is using the regular arduino functions pinMode and digitalWrite to manipulate the pins. So A0 and A1 should work as expected.
Please note that when you use SPI (which the NRF does), you have to use pin 10 (SS) as an OUTPUT (as to not put the AVR into SPI slave mode).

I'd suggest one would use RF24 (by TMRh20) library so that they are actually using a library that has a active developer who's fixing any library related bugs.


text:
Can I specify that analog pins be used for digital output?
http://arduino.cc/en/Reference/pinMode notes that

The analog input pins can be used as digital pins, referred to as A0, A1, etc.

Is it possible to configure these pins as digital output pins as well?

Yes.
http://arduino.cc/en/Tutorial/AnalogInputPins states

The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc. For example, the code would look like this to set analog pin 0 to an output, and to set it HIGH:

pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH)

There are several caveats on that page regarding this.

Good clear answer and very informative link. (voted)

Wait. You answered your own question? Was this a teaching post, or did you find the answer through research after posting your question?

A combination.  I had thought I heard it was the case, but the pinMode documentation wasn't clear. When I found the AnalogInputPins page I thought it would be nice to tie those together.

One more detail: the ATMega 328P in some packages (not including DIP) can support A6 and A7 analog inputs.  While the UNO does not provide pinouts for these (ie: they are unconnected), many clone Arduino Pro Mini boards do.  And these two pins are Analog Inputs only, no Digital I/O functionality.  The other Analog Input pins are as you note also digital I/O compatible.


text:
Arduino Hardware timer and interrupts issue
I recently started programming with Arduino and and currently I'm making a project to read RPM and Speed of my car using Arduino Uno. So far I got everything working but the speed value does not show properly. I have used one hardware counter and two interrupts in this project.

Timer 1 on pin 5 - Count pulses from car's ECU to calculate speed.
Int0 on pin 2 - Read ignition pulse to calculate RPM.
int1 on pin 3 - 5v in from headlight switch to control the brightness of the display (MAX729 7 seg 8 digit).

I can get the proper reading from RPM and also the brightness control is working properly. Here is my codes below.
    #include <LedControl.h>

// inputs: DIN pin, CLK pin, LOAD pin. number of chips
LedControl display = LedControl(12, 10, 11, 1);

//SPEEDO-----------------------------------------------------------
const int hardwareCounterPin = 5;
const int samplePeriod = 1000; //in milliseconds
const float pulsesPerMile = 4000; // this is pulses per mile for Toyota. Other cars are different.
const float convertMph = pulsesPerMile/3600;
unsigned int count;
float mph;
int kph;
int roundedKph;
int previousKph;
int prevCount;
//----------------------------------------------------------------

//RPM-------------------------------------------------------------
//Configuration for the Tachometer variables
const int sensorPin = 2;
const int sensorInterrupt = 0;
const int timeoutValue = 5;
volatile unsigned long lastPulseTime;
volatile unsigned long interval = 0;
volatile int timeoutCounter;
int rpm;
int rpmlast = 3000;
int rpm_interval = 3000;
//---------------------------------------------------------------

//Brightness control---------------------------------------------
int brightnessIndicator = 13;  //Light pin 13 led to show that brightness control is in action.
int brightnessIn = 3;  //Sensor in from headlight positive wire to control the brightness.
//---------------------------------------------------------------

void setup(void) {
  //Serial.begin(9600);

  display.shutdown(0, false);  // turns on display
  display.setIntensity(0, 10); // 15 = brightest
  printTrueno(); //Print my car's name
  delay(3000);
  initToZero(); //Print all zeros before going to the loop

  TCCR1A = 0; //Configure hardware counter
  TCNT1 = 0;  // Reset hardware counter to zero

  //Config for the Tach
  pinMode(sensorPin, INPUT);
  attachInterrupt(sensorInterrupt, &sensorIsr, RISING);
  lastPulseTime = 0;
  timeoutCounter = 0;

  //Config for brightness control
  pinMode(brightnessIndicator, OUTPUT);  //LED output
  pinMode(brightnessIn,INPUT);  //Sensor in
  attachInterrupt(1, changeBrightness, CHANGE);  //Attach the 2nd interrupt
  changeBrightness();  //Check for head lights on or not.
}

void loop() {
  //SPEEDO-----------------------------------------------------------
  // This uses the hardware pulse counter on the Arduino.
  // Currently it collects samples for one second.
  bitSet(TCCR1B, CS12); // start counting pulses
  bitSet(TCCR1B, CS11); // Clock on rising edge
  delay(samplePeriod); // Allow pulse counter to collect for samplePeriod
  TCCR1B = 0; // stop counting
  count = TCNT1; // Store the hardware counter in a variable
  TCNT1 = 0;     // Reset hardware counter to zero
  mph = (count/convertMph)*10; // Convert pulse count into mph. 10x allows retaining 10th of mph resolution.
  kph = ((unsigned int) mph)*1.6; // Convert to kph and cast to integer.

  int x = kph / 10;
  int y = kph % 10;

  // Round to whole mile per hour
  if(y >= 5){
    roundedKph = x + 1;
  }
  else {
    roundedKph = x;
  }

  //If kph is less than 1 kph just show 0kph.
  //Readings of 0.9kph or lower are some what erratic and can
  //occasionally be triggered by electrical noise.
  //if(x == 0){
  if(x < 2){  // 1 was triggered by some noise signal.
    roundedKph = 0;
  }

  // Don't display kph readings that are more than 50 kph higher than the previous reading because it is probably a spurious reading.
  if(roundedKph < 181){
    if((roundedKph - previousKph) > 50) {
      Serial.println(previousKph);
      printNumber(previousKph, 0);
    }
    else {
      Serial.println(roundedKph);
      printNumber(roundedKph, 0);
    }
  }

  previousKph = roundedKph; // Set previousMph for use in next loop.
  //-----------------------------------------------------------------

  //RPM--------------------------------------------------------------
  if(rpm >= 0) {  //Remove the minus values

    //Let's keep this RPMr value under control, between 0 and 9999
    rpm = constrain (rpm, 0, 9999);

    //If the engine is not running, print 0
    if ((micros() - lastPulseTime) < 5e6 ) {
      rpm = rpm;
    }
    else {
      rpm = 0;
    }

    if (rpm < 250)
      rpm = 0;
    //Serial.println(rpm);
    printNumber(rpm, 1);
  }
  //-----------------------------------------------------------------
}

//Each time the interrupt receives a rising tach signal, it'll run this subroutine
void sensorIsr() {
  unsigned long now = micros();
  interval = now - lastPulseTime;
  if (interval > 5000){
     rpm = 61000000UL/(interval * 2);
     lastPulseTime = now;
  }
}

void changeBrightness() {
  int val = digitalRead(brightnessIn);  //Read the sensor value

  if(val == 1){  //If the headlights are on, pin goes HIGH.
    digitalWrite(brightnessIndicator, HIGH);   //turn the LED on
    display.setIntensity(0, 6); //Reduce the brightness.
  }
  else {
    digitalWrite(brightnessIndicator, LOW);    //turn the LED off
    display.setIntensity(0, 14);  //increase the brightness.
  }
}

void printNumber(int v, int flag) {
    int ones;
    int tens;
    int hundreds;
    int thousands;

    if (flag==0){
      ones = v%10;
      v = v/10;
      tens = v%10;
      v= v/10;
      hundreds = v;

      //Now print the number digit by digit
      if (hundreds>0)
        display.setDigit(0,0,(byte)hundreds,false);
      else
        display.setChar(0,0,' ',false);

      display.setDigit(0,1,(byte)tens,false);
      display.setDigit(0,2,(byte)ones,false);
    }
    else if (flag=1) {
      ones = v%10;
      v = v/10;
      tens = v%10;
      v = v/10;
      hundreds = v%10;
      v = v/10;
      thousands = v%10;

      //Now print the number digit by digit
      display.setDigit(0,4,(byte)thousands,false);
      display.setDigit(0,5,(byte)hundreds,false);
      display.setDigit(0,6,(byte)tens,false);
      display.setDigit(0,7,(byte)ones,false);
    }
}

I think the problem is between Timer1 and first interrupt. Can someone please help me to solve this?
Thank you very much.

"So far I got everything working but the speed value does not show properly" - Can you explain more: what are you seeing? what are you expecting to see?  How are you showing the value.  Don't make us work it out from the code!

Have you tried to reduce the program to the smallest amount of code that either works or has the bug, and nothing extra. For example "the speed value does not show properly" is still in the code, but everything else removed. Please answer Will's question first.

Try swapping count = TCNT1; and TCCR1B = 0;. It could be that stopping the counter also resets TCNT1.

@Will - Lets say my current speed is 25kmph. But I'm seeing incorrect random values like 31, 35, 45, 40, etc... Sometimes after every 5-6 seconds I get the correct reading 25kmph. But my RPM values are showing correctly 99% of the time.

@gbulmer When I run these two parts of codes separately (RPM and Speedo), they work without any problems and give me the correct values. But when I merge them together, the speedo value becomes incorrect.

Is the speedo value correct when the value is Serial.print(...) only, and everything using display is removed? I am suspicious about display using a timer or effecting interrupts.

Delete lines from your code until you have it work again then add the last line in again. Simulate inputs with numbers ect... Its very hard to help you like this

I think you made a mistake in the program design.  You have things backwards, and your tach interrupts are messing with program flow because they are happening too fast.
The tachometer runs 0~100 rev/sec.  Send the pulses to the counter and, twice a second, multiply the count by 120 and display the RPM.  You only care what the RPM is to the nearest hundred, anyway, right?
You get an ECU pulse every ~0.4m traveled.  Record the interval (x ms) between pulses in your interrupt routine.  0.4m/x ms * 1 km/1000 m * 3,600,000 ms/hr = ~1448/x km/hr.  Do the (expensive) division, using the last interval recorded, twice a second when you update the RPM.
Now your interrupt routine is getting called every 12ms, tops, instead of 8ms typical.  And, your main loop is running at a steady 500 ms.

else if (flag=1) {

should be
else if (flag==1) {

What else would flag be anyway? Why not just use "else"?

 // Don't display kph readings that are more than 50 kph higher than the previous reading because it is probably a spurious reading.
  if(roundedKph < 181){
    if((roundedKph - previousKph) > 50) {
      Serial.println(previousKph);
      printNumber(previousKph, 0);
    }
    else {
      Serial.println(roundedKph);
      printNumber(roundedKph, 0);
    }
  }

  previousKph = roundedKph; // Set previousMph for use in next loop.

In the code above you admit roundedKph might be wrong, but use it anyway for next time around the loop. That means next time around you will discard a correct reading.

   //If the engine is not running, print 0
    if ((micros() - lastPulseTime) < 5e6 ) {
      rpm = rpm;
    }

What does that achieve?

int rpm;

That should be volatile.


text:
How to connect the INT pin of a MPU 6050?
I am using an Arduino Leonardo together with a GY-521 breakout board (like this one, schematic) for an MPU 6050.
I am currently trying to get the DMP Version of the examples from Mr Rowberg to work.
For all my tests, I use these connections:

GY-521 ->  Leonardo
VCC -> 5V (3.3V has the same behaviour)
SDA -> SDA
SCL -> SCL
GND -> GND

The "raw" sketch works fine, I can read out the sensor data. For the DMP version I think I need to connect the INT pin to pin 3 on the leonardo, to allow the MPU6050 to trigger an interrupt.
But as soon as I connect INT to anything (pins 0 through 3), the sketches do not find the MPU6050 any more. (They report ""MPU6050 connection failed").
Is my wiring off, or is my chip defective, and even more important, how could I figure that out on my own in the future? =)
Edit:
The example source code says
/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

The example does nothing (that I can see) to configure this pin.
Edit again:
I've borrowed an oscilloscope. SDA and SCL sit on 3.3V during normal communication, and I can see packets being exchanged. As soon as I connect the INT pin to any input pin on my Leonardo, both SDA and SCL go to ground. This means nothing to me, but maybe to someone else.

Possible problem: pin interference

But as soon as I connect INT to anything (pins 0 through 3), the
  sketches do not find the MPU6050 any more. (They report ""MPU6050
  connection failed").
Is my wiring off, or is my chip defective, and even more important,
  how could I figure that out on my own in the future? =)

If I'm reading the Arduino Leonardo schematic correctly,
Arduino D0 is Rx, Arduino D1 is Tx,
Arduino D2 is the I2C_SDA, and Arduino D3 is the I2C_SCL.
You're already using the I2C_SDA and I2C_SCL as bidirectional I2C communication;
connecting some other output pin (such as the MPU6050 INT pin) to either of those pins is going to disrupt that communication and then things won't work.
On most Arduinos, Serial.println() and Serial.read() and the reprogramming process use the Rx and Tx pins.
Perhaps connecting the MPU6050 INT pin to either of those pins also causes some sort of problem leading to things that don't work.
(Although the Arduino Leonardo actually uses its USB_D- and USB_D+ pins for both Serial.println() and reprogramming, so maybe it isn't really a problem for the Leonardo?).
I would avoid using those pins for anything other than serial communication, even though I'm not at all sure that would actually cause a problem on the Arduino Leonardo.

The example source code says
  ... this sketch depends on the MPU-6050's INT pin being connected to
  the Arduino's external interrupt #0 pin. ...
  The example does nothing (that I can see) to configure this pin.

I assume you're using https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/Examples/MPU6050_DMP6/MPU6050_DMP6.ino , right?
Interrupts are configured a little differently than I/O.
(In particular, "volatile" is critical to getting interrupts working right).
The part that configures that interrupt is in the setup() function:
void setup() {
    // ...

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
    // ...
}

The "attachInterrupt(0, dmpDataReady, RISING)" line
configures the interrupt vector table and the configuration bits so that when something drives Arduino pin D2 (i.e., external interrupt source 0) from a low to a high, no matter what the Arduino is in the middle of doing, the Arduino puts that on hold, executes the dmpDataReady() function, and then the Arduino resumes where it left off.
I don't see how that ever worked, since "external interrupt 0" comes from pin D2, which on the Arduino Leonardo is connected to I2C_SDA, which we're using for I2C communication, so we can't use it for watching the gyro interrupt pin.
However, since the "attachInterrupt()" gets run long after the "MPU6050 connection failed" message gets printed out on your screen, a software bug in how the example code uses attachInterrupt() doesn't explain why you get that "fail" message printed on your screen.
what to do about pin interference
I would try either using some other pin, or try getting it to work without hooking that pin to the Arduino at all.
Using some other pin
I would try to assign a dedicated pin on the Arduino to the MPU6050 INT pin.
Maybe D9 would work?
I'm guessing on the Arduino Leonardo, the interrupt should be set up something more like:
// warning: untested code.
#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>

// connect MPU6050 interrupt to Arduino D9
#define MPU6050_INT D9

void setup(){
    // ...
    // pin change interrupt
    pinMode(MPU6050_INT, INPUT);
    PCintPort::attachInterrupt(MPU6050_INT, dmpDataReady, RISING);
    // ...
}

Getting it to work without hooking INT to the Arduino
It's not at all clear that the Arduino really needs to be connected to the MPU6050 INT pin.
It appears that another option is for the Arduino to occasionally use the I2C communication to read the status of the MPU6050, which includes the current state of that pin.
That simplifies the hardware -- simply leave the MPU6050 INT pin unconnected.

possible problem: level mismatch
I speculate that maybe some output on this Arduino is trying to push close to 5.0 V into your gyro, which is well outside the specifications of your gyro.
You are lucky that anything worked at all.
According to page 12 of the MPU-6050 gyroscope datasheet,
the gyroscope is designed to operate from a power supply of VDD = 2.375V to 3.46V.
You might think that is already taken care of by the 3.3V regulator on your breakout board.
However, a VDD of 3.3 also implies that the gyro expects all of its inputs to be in the range 0 V to 3.3 V, and the gyro will drive its outputs in the range 0 V to 3.3 V.
Page 358 of the ATmega32u4 datasheet says that the ATmega32u4 is designed work with any power supply in the range 2.7V to 5.5V.
There is a 3.3V regulator on the Arduino Leonardo and another one on the GY-521 breakout board.
So the GY-521 breakout board should have its VCC connected to 5V and its GND connected to the Arduino GND so that regulator can power the gyro chip with 3.3.
Unfortunately for you, the Arduino Leonardo is designed to power the ATmega32u4 with VCC = 5.0 V.
What to do about level mismatch
Perhaps it would work better if we connect things the way they were designed to be used.
If I were you, I would try to keep signal levels within specifications by any one of:

Use a level converter, perhaps a I2C-compatible level converter for each data connection between the 3.3V I/O pins of the gyro and the 5.0V I/O pins of the Arduino Leonardo. (a) (b) (c) Or,
Somehow tweak the Arduino Leonardo to connect 3.3 V to the VCC pin of the ATmega32u4. (Does this require cutting traces on the PCB?). Or,
Use some other Arduino configured to run the processor at 3.3V (LilyPad Arduino USB; Arduino Fio; Arduino Zero; Arduino Due; Arduino TRE; some versions of Arduino Pro Mini; some versions of Arduino Pro; etc.) or easily connected to 3.3V (LilyPad Arduino SimpleSnap;  LilyPad Arduino Simple; LilyPad Arduino; etc.)

Is it possible that the INT pin on the MPU 6050 in an input, not an output?
The symptoms you describe make it sound like you're locking the gyro chip into an interrupt state so it's not responding any more.
I wasn't able to figure out the use of the INT pin from a quick scan of the data sheet however. It would take more careful study.
Do you have your Arduino pin set up as an input or an output? And if it's an input, does it have a pull-up or pull-down resistor, either internal or external, set up?

Thanks for your input. I'll need to check how the pins are configured; I only use the example code linked in the question and have nothing configured myself. The INT on the MPU should be an output. This setup works for others (at least with a Uno).

To use external interrupt 4 (INT6), pin D7 on Leonardo board. we need change interrupt register as follows
   EICRB |= (1<<ISC60)|(1<<ISC61); // sets the interrupt type
   EIMSK |= (1<<INT6); // activates the interrupt

that write in WInterrupts.c
Follow this link
http://forum.arduino.cc/index.php?topic=124057.0

the interrupt pin in the attachInterrupt command should be kept to #4 which is pin D7 as stated here "http://arduino.cc/en/Reference/AttachInterrupt" since we can't use pins D0-D3 the only left out option is D7 but the problem still persists. Somebody please solve this !!


text:
When setting hardware timers as interrupts, should I prefer a lower prescaler value or a lower CTC?
I'm currently playing with Arduino's hardware timers, and a question came to my mind. Let me explain it a bit.
Let's suppose I want a certain function to execute every 1024 clock ticks. AFAIK, I could achieve this in several ways, playing with the prescaler value for Timer2, and its CTC:

Setting the prescaler to 1 and the CTC to 1024
Setting the prescaler to 8 and the CTC to 128
...
Setting the prescaler to 1024 and the CTC to 1.

All these ways would achieve what I want, but, which one is more efficient? Or it doesn't matter at all?
Thanks in advance for sharing your knowledge :P

Larger prescaler values will result in a very slight decrease in power consumption as whatever circuitry is connected to the output of the prescaler will switch at a lower frequency, and power consumption is proportional to c v^2 f.

CTC is not a number, it's a mode of operation of the counter (mode 2). You set the period of the timer by setting OCR2A, the actual period being (OCR2A+1)×prescaler CPU cycles. Thus, if you set the prescaler to 8, you have to set OCR2A=127.

If 'clock tick' count (here 1024), timer width and  MCU clock used are constant (a fixed value), I would not go for last option i.e. prescalar 1024 and CTC of 1. Here are my reasons (specially for Arduino )
1) When CTC is close to zero ( like 1-> 10), sometimes timer behaves as if count is zero and outputs a square wave (with 50% duty ratio) with half the demanded frequency. So make CTC reasonably big. But again selecting a high clock frequency (pre scalar 1) may also show reduced accuracy. A intermediate option I think is better.
2) When count CTC changes dynamically in a process, timer pre scalar should be selected such that CTC count will always be less than or equal to timer width over whole process.
i.e. the maximum 'timer tick count' should be comfortably accommodated by the timer with it's given width. Even here same dilemma again occurs, then selection based on point 1 is better.
If this is not enough, then only way I think is to implement each case  physically and check which combination gives you the best results. Practical results I think are more reliable ( may be you will get a board specific efficient combination!)

I don't see any reasonable root cause to validate your remark about low CTC values that may reduce accuracy. In particular, the "sometimes timer behaves..." is obviously wrong: why would timers in the AVR architecture would have not repeatable behavior in this case?

I said low pre scalars (not CTC values) may reduce accuracy. Low CTC values may give unwanted outputs from timers.

'Sometimes' here means for 'some boards' of Arduino. I used this word because question not was asked for specific board. I have many times worked with 'Arduino Due' timers, with timer frequency 10.5 MHz and whenever I gave CTC count  less than 15 ( or near by ) timers gave me a square wave, so obvious reason is that count is taken as zero. This is not mathematical but a practical observation. As said I have only worked with 'Due' for my purpose which is an ARM ( not AVR with lesser clock frequencies used in Arduino ) and so using 'sometimes' is valid I think.

There is a trade-off between resolution and achievable frequencies. You mention Timer 2, but on the Atmega328P Timer 2 is an 8-bit timer, thus you would not be able to set the CTC to 1024.
Let's assume we are talking about an 16-bit timer, like Timer 1 on the Atmega328P. With a prescaler of one, you can time (assuming a 16 MHz clock) from 1 to 65536 "ticks", that is 62.5 ns up to 4096 µs.
This would be the most precise measurement because you are using one (processor) clock tick per timer tick (a prescaler of one).
However if you plan to time for more than 4.096 ms then you need to bump up the prescaler. The next prescaler up on Timer 1 is 8, so now you can time for an interval 8 times as long (32768 µs) however your accuracy (precision) has now decreased by a factor of 8. The granularity of the timer has increased from 62.5 ns to 62.5 * 8 ns, which is 500 ns.
If you need to time longer than 32.768 ms then the prescaler has to be larger again, the next one being 64. So now you can time up to 262144 µs, but with a granularity of 62.5 * 64, which is 4000 ns (4 µs).
My suggestion would be to use the lowest prescaler that you can, but still get the interval you want. So obviously you can't use a prescaler of one to time 10 ms.

I have a discussion about timers on http://www.gammon.com.au/timers.
On that page is a chart which helps visualize the effects of different prescalers:

The top part (count of one) effectively gives you the granularity of each prescaler. For example, a prescaler of 256 has a granularity of 16,000 ns (16 µs). Certain frequencies (powers of 2) will lend themselves to combinations (eg. prescaler of 1 with a count of 256, or prescaler of 256 with a count of 1).
However for frequencies that don't have that property, the smaller prescaler will (if it can be used) give a finer granularity.

Using a higher prescaler does not loose any precision at all. You do get bigger granularity, but if you target a cycle count that is a power of two (like in the question), granularity is not an issue.

But if not, then the lower prescaler lets you get closer to the target. Say you want to time 30 clock cycles. A prescaler of 1 lets you enter the number 30 directly. A prescaler of 8 means you have to use 30 / 8 (3.75) which you cannot directly enter into the register, thus losing precision.

The question was worded with 1024 counts, so my remarks don't apply to that, but I was trying to give a more general answer, in case the fact that 1024 is a rather special case wasn't obvious.


text:
Difference between PWM and regular output port for servos?
I have been controlling my servomotors for a while now only using pin 0. After some research, it has became apparent to me that the ports with ~ are the PWM pins.
I thought that all pins sent out PWM signals, therefore the motor was able to move back and forth. Now I'm really confused as to how the motor was able to turn without using a ~ pin like pin 5.
Can someone explain why I should or should not use PWM signal when controlling a motor?

Servos does not use PWM, it uses PPM:

PWM = Pulse width modulation, The pulse start at 0ms, and is high for the percentage of the time compared to the percentage of the voltage you want, 5v signal, if you want 1v, the pulse is 20ms High and 80ms Low.
PPM = Pulse position modulation, The pulse length is always 5ms High and 95ms low, but the interesting part is if high starts after 5ms or 50ms (or any other).

So PWM is to lower voltage, PPM is a signal pulse.
This means that no matter what port you are using on the arduino you are able to control a servo since you only need High or Low, and not a lower voltage.
What you need to be aware of in this case is on the arduino is a PPM signal is using up a timer. The arduino has 3 timers where of 2 is available, one is used internally. Though there is code where you can attach up to 3 servos on the same internal timer.

Just 2 links describing this better than i did:

http://www.endurance-rc.com/ppmtut.php
http://forum.arduino.cc/index.php/topic,14146.0.html

PWM doesn't change voltage. It just changes the duty cycle. If you setup the timer correctly you might be able to have it do PPM (pulse position modulation). But you would only be able to control one serve per timer.

@Gerben sure PWM does not change voltage, but the effect of a 50% duty cycle of a 5v battery is roughly the same as just attaching a 2.5 volt battery, and to be exact you want to add a filter behind it to get the lowered voltage. But since i don't know my target audience i try to make it as basic as possible.

@Gerben Also edited wrong term, thanks for the correction.

-1. Your description of PWM vs PPM is correct, but you're wrong when you say servo control is PPM. It's PWM. Typically you'd vary the pulse width between 1ms and 2ms to control between fully left and fully right. See for instance this image.

@JorisGroosman Just fyi, it appears that servos and recievers (and flight controllers) comes in both PWM and PPM. so it appears we are both right.


text:
Reading many analog signals in arduino
I need to measure around 50 - 100 analog sensors (resistors). This poses two challenges:

Arduino has fewer analog pins. I'm targeting something small like arduino Mini or Nano, which can have up to 8 analog pins. The solution for this could be several multiplexors like this one. Is there a better option? Is this the best way to read so many analog sensors with Arduino? I am thinking also in several arduino mini talking through wifi / bluetooth with the main one which would also aid with Problem #2.
There would be a lot of cables for this setup, and I need to keep it all as flat and flexible as possible. So I was thinking of some kind of adesive copper conductor, paper printed circuit or plastic. The thing is that it would become difficult to create if I do it myself. What would be the easiest way to achieve a multi-track, flexible circuit for substituing Arduino cables?

Depending on your performance needs, you could look into a multi-channel ADC with an I2C interface.  Then you can use a single I2C bus to read all of the analog signals.  This may not work if you need to read the signals faster than the I2C bus would allow.

Your question doesn't specify speed, cost, accuracy, or size, and it skimps on electrical and physical details (referring merely to 50–100 resistors and “a lot of cables”) so perhaps can't be properly answered.
ADC's (analog-digital converters) typically are high-impedance devices that measure voltages.  A resistor may be measured in many ways, a few of which are:

Place a known voltage across it; measure current through it
Drive a known current through it; measure voltage across it
Drive some current through it; measure both voltage and current using four-terminal sensing
Measure how long it takes a given capacitor to charge to a trip point, using a known voltage through the resistor under test
Use known resistances to null a Kelvin bridge

For some of the techniques listed above, measurement accuracy is little affected by multiplexer resistance; others might need to use a low-resistance MUX made with relays instead of a MUX ic like the 74HC4067.  Some of the techniques are suitable for wide ranges of resistance, others not; and some for high accuracy, others not.
Suggested Approach
Anyhow, those comments aside, circuits like the following might do the job.  If you have eight analog inputs on your Arduino, you could use up to eight multiplexers to measure up to 128 resistors.

In Figures 1 and 2 above, Rx is a typical unknown resistance, and Rs is a known standard resistor.  Both figures represent voltage divider circuits.
Effect of multiplexer transmission gate resistance
Let Rm denote multiplexer transmission gate resistance.  Rm is unimportant if the circuit of Figure 1 is used because Rm is tiny compared to the input impedance of a unity-gain follower op amp stage.
Rm might or might not be important if the circuit of Figure 2 is used. (a) If Rm differs somewhat from one multiplexer channel to another, Figure 2 may be unsuitable because calibration will be cumbersome.  (b) If Rm is comparable to Rx, Figure 2 is unlikely to produce high-accuracy results.
Whether unity-gain followers are necessary
Whether you need unity-gain followers depends mostly on the size of resistors you are measuring.  Arduino analog inputs are high-impedance (10⁸Ω, but with about 14pF capacitance to Vcc/2).  Atmel suggests analog source impedances of 10KΩ or less for best results.  [See (1,2,3) for additional discussion.]  Briefly:  If Rs+Rx is likely to exceed 20-40KΩ and you wish to measure quickly, use unity-gain followers.
Resistance Formulas
Let Vt be the voltage at the lower end of Rs in either figure.  Vt is the voltage that will be measured at an analog input Aj.
In Figure 1, because Vt = Vcc·Rx/(Rx+Rs), we have Rx = Vt·Rs/(Vcc-Vt).
For the circuit in Figure 2, an additional resistance Rm is in series with Rx, so Vt = Vcc·(Rx+Rm)/(Rx+Rm+Rs), whence Rx = Vt·Rs/(Vcc-Vt)-Rm.  If Rs and Rx are large (eg 40KΩ and 10KΩ) then ignoring Rm may cause only a fraction of a percent of error.  But if Rm is comparable to either of Rs or Rx, either use the circuit of Figure 1 or devote some inputs of each multiplexer to use as calibration inputs.
Analog input reference voltage
If Vcc is 5 V and we choose Rs four times as large as the largest resistance value that you intend to measure, then Vt will be between 0 and 1 V.  You can use an analogReference() call like analogReference(INTERNAL) [or analogReference(INTERNAL1V1) on a Mega] to set the analog reference voltage at 1.1 V, to maximize accuracy of measurement and to minimize the amount of current required through Rx.
Advantages of Figure 2
Unless Rm is a problem (as discussed above) the following advantages of Figure 2 suggest its use:

Lower power requirements:  In Figure 1, all the resistors under test always have current going through them.  In Figure 2, only 1/16 of the resistors are powered at any given time.  Also, by raising \EN to shut down the 4067's (or 74HC4067's if used) all the resistors can be powered off.
Less wiring and fewer parts:  At most eight Rs parts are needed, rather than one Rs per Rx.  Each Rx connects to ground and to one mux input, rather than to ground and to the junction of a mux input with an Rs.

Cable Note
For either figure, seven or eight wires run from the Arduino to each 4067 subcircuit.  One wire from each subcircuit carries Vt back to an analog input.  The other wires connect to all subcircuits in parallel: four channel select lines (A, B, C, D in figures, or S0-S4 in datasheets); Vcc; ground; and \EN unless that line is wired to ground.  Each 4067 subcircuit should have a bypass capacitor, eg 10-100 nF, from Vcc to ground.  Boards like the “Geeetech CD74HC4067 Analog Digital MUX Breakout Board” shown below (about $5 on ebay) might be used, or you could design a custom board and have it made at OSHPark or Seeedstudio.

As I read your question I was thinking of the 4067 chip as part of the solution.
You'd rig one 4067 as the anode and another as the cathode on a grid of 64 resistors. You'd then send select an anode channel and a cathode channel, feed +5 volts into the common for the anode channel, and then feed the common from the anode channel into an ADC input on your Arduino. You'd need to allow for the fact that those chips have an internal resistance of around 180 ohms, (at least the TI chip I looked up did. My CMOS cookbook lists 200 ohms resistance.) As long as you're measuring resistances that are substantially bigger than 400 ohms, that should work (or you could precisely measure the resistance of your 4067 chips at your operating temperature and then adjust your math to compensate.)
Mind you you'd have to sample these resistances one at a time, in round-robin fashion. It would be kinda slow.
If you want to test more than 64 resistances, you could use 2 4067s on either the anode side or the cathode side and use the inhibit pin to select the chip. That would give you the ability to sample 128 resistances.
I did find some 8 and 16-channel serial ADCs. You could use those and some select logic to do the same thing. Take a look at the AD7490. That's a 16 channel serial ADC. That and one of the 4067 16-channel MUX chips would give you 64 ADC inputs in banks of 16.

This will only work if you add diodes in series with all of the resistors and account for the added diode drop.  Otherwise, all of the other resistors connected will significantly affect the measurement.

Not true. With a row and column arrangement of MUX chips, you can connect +5 to one wire of the test resistor and then read the voltage through the other MUX chip.

Let's call the wires drive wires and sense wires.  The drive MUX drives one drive wire to 5v.  The sense MUX then selects a wire to check the voltage.  There is a test resistor that connects each sense wire to each drive wire.  The problem is this:  the sense wire is connected to other drive wires by other unknown resistors, so whatever you do with the other drive wires (grounded or floating) they will affect the measurement of the 'unknown' resistor you are trying to measure.  Either you need one mux pin per resistor, or you need one diode per resistor to isolate a single resistor.

CMOS MUX chips and one-of-n chips have nearly infinite impedance when they are in the open state. Thus, only one path from 5V (drive wire) will be "hot" at any one time, and only one path from the sensor to the arduino (sense wire) will be connected. All other drive wires and sense wires will be open circuits. This would be much easier to describe if I could create a CircuitLab picture of it.

You want to do something like this with resistors, correct?  http://xronosclock.com/home/wp-content/uploads/2014/02/LedMatrix.jpg  The only reason you can get away with this with LEDs is because current can only flow one way through an LED.  If you try this with regular light bulbs, then quite a few of them will light up if you apply power across one row and one column.

No no no no. That is not true. You put a MUX on the rows, and a MUX on the columns. You connect the common on the column MUX to +5V. You connect the sensor line to the row MUX common. You put the resistors you want to measure connecting each row/column. Each MUX chip only connects one row or column. If you select column 0, row 0, you're running +5 v though the "anode" of resistor 0,0, and sensing the output voltage from the "cathode" of that resistor. None of the other resistors has a path between +5 and the sense pin, so they have no impact on the resistance.

And yes, you could also use the same rig with lightbulbs (not LEDs) and light 1 and only 1 lightbulb. I'll make a substantial bet on this, and I'll win. The thing you CAN"T do is connect switches at each address in the grid and figure out what's going on when more than one switch is pressed at a time.

Nope.  No other resistor will have a DIRECT path. But there will be a large number of paths that pass through 3 resistors.  Take a look at that figure I linked to.  Replace all of the LEDs with unknown resistors.  Leave all rows and columns disconnected, except for row 0 and col 0.  Current will flow through the resistor at 0,0.  However, it can also take a path through 1,0 then 1,1 then 0,1 and get to the same place.  Or 2,0 then 2,2 then 0,2.  You can come up with a great many paths like this that will all appear in parallel with the resistor you're trying to measure.

If you replace the LEDs with lightbulbs in the same configuration, then the bulb at 0,0 will light up brightly.  However, ALL of the other lightbulbs will also illuminate as current can take the same set of paths through 3 bulbs to get to the same place.

You're right. I was wrong. My scheme would require a series diode on each unknown resistor to prevent current from flowing backwards through the resistors as you described.

Also, one more thing to note: if you put diodes in there, you are going to get a 0.6 to 0.7 volt drop across the diode, which will have to be accounted for.  If this is constant, then it is a simple matter to compensate for this digitally after taking a reading of the voltage.  However, it is possible that this will vary significantly with current, so you may need to do something a bit more clever.  You need a resistor to ground at the ADC input to put the unknown resistor into a voltage divider.  Perhaps taking two measurements with two resistors would allow the diode drop to be removed.

So what was the bet from???


text:
Cheap Wired Multipoint Mesh Network
I'm looking to make a 15 x 15 grid of load sensors and RGB LEDs for an interactive dance floor. Each node will be driven by an arduino and the entire floor will be managed by a RaspberryPi. I'm trying to figure out the best way to have the nodes communicate with the Pi. Ideally the network would have these characteristics:

Low cost per node
Raspberry Pi as the master, arduino nodes as slaves
Ability to know where each node is in the grid
Healing: If a node goes down it doesn't take out all the others.
Can easily replace broken nodes
The electronics for each node will be ~12 inches apart
The master will be 5 - 10 feet away from the matrix.

So far I have been toiling over a few ides.
I2C
This would allow each node to be addressable, however, it seems that Arduino will only allow up to 127 addresses and this matrix will have at least 225 nodes.
SPI
If daisy chained it would be easy to know where each node is in the matrix. But if one node were to break all the nodes after it would stop communicating. (right?) I could have each row daisy chained separately, so if one goes down it only affects that row.
1-Wire
1-wire also looks promising. I'd have to figure out my own way of determining node placement, which could be achieved a variety of ways.
Custom Serial
Each node has a serial connection (rx/tx) for each of it's four sides. This would allow it to communicate to each of it's neighbors directly and pass along messages that are not addressed to it. If one node were to go down, the message would be automatically routed around the broken node since there are several paths to each destination. This option is a little crazy and I'd prefer to avoid something so custom and convoluted.
USB
This would require a USB hub in each node.
XBee
Too expensive.
Other thoughts or options?

Since you did mention XBee, nRF24 nodes are ridiculously cheap and can be mesh networked.

Would they scale to a system of 225+ nodes in a close space?

I don't see why not, each radio can listen to 6 other radios at once.

Seems to me that an Arduino per node is not a cheap way to go. Those are fairly expensive general-purpose devices. Why not build a simpler custom board based on one of the AVR chips like an ATiny? If you're building 225 nodes then $30/node gets really expensive.

Ultimately doing a custom AVR per node is the plan. I'll just be prototyping it with arduino first. Each node doesn't even need to be smart, so it would be even better if I could find a simple way to mux/demux the input/output from each panel without a microcontroller.

I'd probably skip the self healing and do a daisy chained asynchronous serial (probably bit-bang in ATtiny).  Perhaps modeled on DMX LED rope byte-peeling you could do something where each node peels a byte of command off the front and adds a byte of sensor status to the end before forwarding the message.  A failure would mean one pixel goes dead (or stuck) and no data comes back, but you could easily see and replace that one.  Electrically  skip the grid and just do one snaking linear chain, or perhaps several if you can't move enough data on one line.

For I2C you can try http://www.linear.com/product/LTC4312
This will allow you to make two I2C networks to address all the nodes.
However, the wiring for I2C will be a nightmare, but it might be necessary if you want the nodes to be independent.

I think I would use RS-485.
With this standard, you can write your own communication-protocol and with arduino it is easy to use with the Serial class. As extensions for the Arduino you only use the MAX485 because it uses the UART-cip of the Arduino.
I have absolutely no experience with the rasperypi but I think it does also have an UART-Cip what would mean, that you can also connect the MAX485.


text:
Internal volts in arduino for percent battery
I'm working on a small project that is creating me a headache. I know arduimo (ATmega 328P .... etc. ..) has an internal voltage source code millivolts, but I would like to know how the full source code become percentage where 3 volts = 0%  and 4.2 volts = % 100% ??? . I appreciate the help because in codes is not my forte. I leave the code so Help me complete. Thank you.
long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println( readVcc(), DEC );
  delay(1000);
}

Are we talking about the calculation X = (V - 3)* 100/(4.2 - 3) where V is the voltage (in volts) and X is the percentage?  When V = 3 this gives X = 0, when V = 4.2 this gives X = 100

@jim readVCC() returns a voltage in mV, so adjust for that and add as a answer :D

Mind you that the band gap reference is reasonably stable over time, but its absolute value in not very accurate. You may want to 'calibrate' the returned result from your readVcc function.

The charge on my arduino and something I'm doing wrong it gives me error :-(

Where did the code you posted come from? That's some pretty cryptic code.

"3 volts = 0% and 4.2 volts = % 100%" This sounds a lot like you are dealing with a battery, probably lithium of sorts, and you should be aware that battery remaining charge has some very non-linear regions. You will need something more complicated - a higher order equation, multiple regions, or a lookup table and interpolation.

Hello Duncan C sorry for replying so late but my job car electronics I removed my long wire-level and breakdowns but not at the programming level (low level) and I'm trying to develop a car burglar alarm so I need help . The source code I've taken from this website .  https://code.google.com/p/tinkerit/wiki/SecretVoltmeter

Hello Chris Stratton, if it comes to lipo batteries and discharge curve I got from this website: https://learn.adafruit.com/li-ion-and-lipoly-batteries/voltages

map()
unsigned char level = map(readVcc(), 3000, 4200, 0, 100);

You need to find a C language tutorial very badly, because you have no clue what you're doing, and you're not doing yourself or anyone else any favors like this.

sorry did not mean to, I just needed help, so asked.Thanks anyway

I do not in any way mind answering questions. The thing is that the fundamentals required to understand my answer are missing. Please take some time to familiarize yourself with C language structures.

@IgnacioVazquez-Abrams, I agree with your comment about needing a grounding in C. However, your answer uses the map function, which is part of the Arduino libraries, not straight C.

@DuncanC: Sure, but understanding how functions and function calls work and interrelate is.

Any idea why there's no comment button on the original question? I want to see if the code is the OPs or somebody else's.

@DuncanC: I'm almost certain it's not theirs.


text:
Break statement terminating loop()
I am experiencing some very strange behavior with my arduino. I have a switch-case statement in the loop() method, and the break methods are not only breaking out of the case block, but also out of the loop() statement. Is this normal, and if so, how can I edit the structure so it doesn't do that?
My code structure looks like this:
void loop(){
  switch(int i){
    case 1:{
      //do something
      break;// this also breaks out of the loop() method.
    }
  }
}

I'm closing this because the source of the problem turned out to be unrelated to the original question.

I just realized it wasn't the sketch, but a faulty SD card reader on my computer corrupted my SD card. BIG TIME.

Ok, I guess you should accept your own answer. That or delete the question. I still stand by my statement that you need a way of displaying debug information or you're going to drive yourself crazy.

@DuncanC Yeah, good point.

@DuncanC I have to wait one more day.

Your sample is too simple to test your hypothesis (which is wrong, by the way.)
Set up serial output so you can test:
void loop()
{
  Serial.println("Before switch statement");
  int i = 1;
  switch (i)
  {
    case 1:
      Serial.println("In case 1");
      break;
    default:
      Serial.println("In default case");
  }
  Serial.println("After switch statement.");
}

You can even add an outer for loop to make things a little more complicated:
void loop()
{
  Serial.println("Before for loop statement");
  for (int i = 1; i< 10; i++)
  {
    Serial.print("In for loop before switch, i = ");
    Serial.println(i);
    switch (i)
    {
      case 1:
        Serial.println("In case 1");
        break;
      default:
        Serial.println("In default case");
    }
    Serial.println("After switch statement.");
  }
}

Examine the output on the serial monitor of your computer. You should find that the "After switch statement" line always appears after the "before switch..." line in both versions of the code.
Break breaks from the innermost scope. If you have nested levels of scope, like a function and then a switch statement inside the function, the break statement breaks out of that inner level. In the second example, the break broke out of the switch but the for loop kept running.
This is very basic C programming and not specific to Arduino.

The thing is, I'm running the MCU of my arduino in a completely different board, so I can't use the serial monitor.

Uh-oh. Hook up an LCD display then? Or better yet, get a C compiler for your computer and learn the basics of C that way. As I say, your questions are on vanilla C, and not at all specific to the Arduino. You're going to spin yourself in circles trying to develop when you don't know the language and can't even add debugging statements. (I do my day job with an integrated symbolic debugger that lets me add breakpoints, examine variables, etc. The Arduino with it's limited debugging tools is a step backwards. Take away print statements and you're stumbling around in the dark.)

Never mind!! I just realized the sketch isn't broken, but instead one of my SD cards was corrupted.


text:
Is setup and loop provided for convenience?
Arduino sketches usually feature a setup and loop function. Are these functions only provided for convenience or do they actually have special purposes? (e.g.: are some operations disallowed or allowed in setup and loop)
Are these two pieces of code equivalent:
Classic
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
}

Without loop
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);

    while(true) {
        digitalWrite(LED_BUILTIN, HIGH);
        delay(1000);
        digitalWrite(LED_BUILTIN, LOW);
        delay(1000);
    }
}

void loop() {
}

Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

Those pieces of code are pretty much the same.
If you look at the Arduino source code you'll see:
setup();

for (;;) {
  loop();
  if (serialEventRun) serialEventRun();
}

(I'm not sure what serialEventRun() does.)
I don't think you can 'overload' the main function declaration. Also note that the main function calls init, which e.g. configures the timers, so millis() etc. will work.

Are these functions only provided for convenience or do they actually have special purposes?

The Arduino libraries do a tiny bit of housekeeping with loop(), related to serial handling.

Are these two pieces of code equivalent:

Only if you never use serial events.

Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

Not while strictly using the Arduino libraries via the IDE; the linker will complain of either duplicate main definitions or of missing setup or loop definitions.

Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

The last time I used the IDE, you could have a project with no .ino/.pde file, only .cppfiles; since it's the mangling of the .ino into a .cpp that defines the main function, if you bypass that step then you can define your own main.
If the IDE no longer allows this (as I've heard) you can still do the same thing with e.g. a Makefile-based build outside the IDE, without giving up the Arduino libraries. The caveats that I know of are:

You should #include "Arduino.h" if you want access to the library functions.
You should call init() if you want the library to set up peripherals the way you're used to.
You should put the serialEvent code that Gerben points out in your mainloop if you want a serialEvent handler to run (but you probably don't need this anyway if you want to write your own mainloop).

Arduino sketches usually feature a setup and loop function. Are these functions only provided for convenience or do they actually have special purposes?

They throw in an extra function call to init which initializes the timers which let millis, micros and delay work without further effort. Other than that, no.
This code compiles (and runs) under the IDE:
int main ()
  {
  }

Effectively the IDE generates code like this:
int main ()
  {
  init ();  // set up timers
  setup (); // your own initialization
  while (true)
    loop ();  // stuff you want to keep doing
  }

They have fiddled with it since then, as Ignacio Vazquez-Abrams said, but basically you can ignore that. There is nothing particularly special about setup and loop.
You can use main like I showed above. You can do everything in setup if you want. You can do everything in loop if you want (if you never return from it).
Remember, you are dealing with a C++ compiler here. Functions don't have some magic significance based on their names.


text:
Arduino not responding
I have been using my arduino uno for many months and it worked very well even till today morning but an hour ago I tried to upload a sketch and arduino IDE showed my this "avrdude: stk500_getsysc(): not in sync: resp =0x00" , at first I thought maybe I burned my atmega32 chip but I bypassed reset and gnd with a jumper wire and opened serial monitor and my atmega32 still printing serial data,so problem must be something else,and also my led13 isn't blinking.Is it problem with bootloader?if so how can I reload bootloader in my board without using another arduino?

I'm personally not really in to this RTFM kind of answer, but in this case it really do answer most of your questions about the bootloader part: http://arduino.cc/en/Hacking/Bootloader
About the error, a quick search on SO gives you this: https://stackoverflow.com/questions/24240285/arduino-nano-3-avrdude-stk500-getsync-not-in-sync-resp-0x00


text:
Arduino + simple DC motors? (4WD kit)
I am trying to connect 4 small DC motors to Arduino, like those in the following image:

The specification for each of them is:

Suggested Voltage: 3V DC;
  No Load Speed: 65 ± 10rpm;
  No Load Current: 125mA (170mA MAX).

But I have no useful knowledge in electronics to do so...
I would be really thankful if anyone could explain me why it is so difficult to connect DC motors to Arduino (I've heard about problems with the magnetic field, but I don't really understand why); and possible point me to an easy (and cheap) solution. I am, of course, willing to study (not expecting a complete solution).
I'm aware there are some shields for doing this kind of connection, but they are really expensive, and I've seen some people using only transistors or components like SN754410.
Thank you in advance! :-)

It's not really the no-load current you need to know, but rather the load current.  Those look suspiciously like the type of low-voltage, high-current motor which is hard to drive, such that many people replace the actual motors in the gearboxes with others.  But if you want to try, consider an FET H-bridge like the TB6612FNG, probably already on a PC board.

@ChrisStratton, thanks! I am planning on using a L298N driver motor; wiring the two left motors together and the two right motors together (being able to use a single dual H-Bridge). Would you happen to know if this configuration would suffice? :-)

may i ask where you got that kit ?

I would not use the L298 in a battery powered application - the losses are a bit high, in particular you will drop more than a volt across the two transistors.

Thank you, guys! I have used the L298 and it was perfect. :-)

@Magic-Mouse, I have bought them with a reseller in Brazil. But they are easily found on Google (try googling the image itself on google images).

First you make 4 parallel H-Bridges, http://en.wikipedia.org/wiki/H_bridge then you attach it to an external powersource ( or attach directly to the battery to prevent burning your arduino )
Attach every up to a pin, making it high makes the motor running, you need 8 pins for this, eg pin 1 makes motor 1 go forward, pin 2 makes motor 1 go back and so.
This is by far the most practical solution, but it is the easiest, and can be done with 8 PNP and 8 NPN transistors.
If you don't know how transistors work i suggest https://www.youtube.com/watch?v=-td7YT-Pums collins lab, it is both educational and entertaining.

Making your own H bridges from discrete transistors is probably not the best solution here, especially for a poster facing this for the first time.

Just wire 2 motors to turn forwards, and 2 to turn backwards. That way you don't need an H-bridge (which in theory is easy to make, but in practice can be difficult to do right, I'm told).

@Gerben true true, but this is 4 motors attached, i was just afraid that the current going through them would be more than the arduino could handle, thats all. (Besides it is fun to play with H-Bridges, since it is the first step for a stepper motor. No pun intended)

@Gerben The Arduino does not handle more than 40mA on an IO pin (according to documentation) and 200mA on the Vcc pin meaning he could only run 1 motor or risc frying the board.

@Gerben and Magic-Mouse, Thanks! I am planning on using a L298N driver motor; wiring the two left motors together and the two right motors together (being able to use a single dual H-Bridge to control left or right). Would you happen to know if this configuration would work? :-)

Yes the L298N is perfect for that since it supports up to 4 amps of current so you could serial couple about 23 of those motors without frying it.

@Magic-Mouse - the Arduino would not be able to run even one of these motors.

@user282723 grad you choose to use a dedicated H-bridge chip. The L298N should work. You can just connect the two motors in parallel.

Thank you, guys! I have used the L298 and it was perfect. :-)


text:
Using Arduino Nano as USB Host
I'm pretty new to microcontrollers and Arduino and since I can't find any satisfying information on my problem, I hope that you might answer them:
My project is actually quite simple: I just want to write out data over a serial connection via USB, the problem: My Arduino Nano has to run as USB Host. That's because the other device is a vacuum cleaner: Neato XV-25 with a mini usb jack. I was already able to 'talk' to it using a Raspberry Pi.
Since I don't have much knowledge about USB communication, I would like to know the following, before I start digging deeper:

I found out, that I would not be able to use the 'usual' usb port of the nano. But I've read a few things about that 'V-USB' library, but did not understand very much. Would it be possible to create a USB Host with this library, that can communicate via a virtual serial connection?
I stumbled across the USBHost for Android Nano. It's a shield, but I'm not sure if it would fit my needs. Is it able to handle serial communication? And is there somewhere a store where I can get it cheap? I think more than 20$ for a shield is a bit too much...

I'm sorry, I just saw another post and realized, that hardware questions are not tolerated, but i still think, that at least my first question counts as a software-based question...

Realistically, by the time you put a USB host shield on an Arduino you might as well just get a raspberry pi model A.  Or you can look at various other embedded boards with USB host capability - STM32F4 discovery - but you may have to learn more to write the software for it.  It would also be useful to check what driver is being used on the pi, as if it is one for a stand alone chip, that suggests you could modify the target to get at a logic-level UART behind the USB-serial chip.  Conversely something like CDC/ACM suggests you may be talking to a USB-device port on the main micro.

V-USB is a software-only implementation of a low-speed USB device for Atmel’s AVR® microcontrollers

No host support here, sorry.
The USB host shield handles the hardware bit and simplifies the software bit. It is up to the firmware to support the various USB profiles. Version 2.0 of the library supports CDC with a few devices; check to see if they would be correct for your purpose.


text:
Is it bad to leave my Arduino UNO on uninterruped?
I'm developing a project (Data logger) that requires that the Arduino remains on for several weeks.
Is it okay to leave it on for about 6 weeks? Do I need to frequently reset it?

Should be just fine. Just like you can keep your PC on for 6 weeks (webservers are on 24/7). If your code is correct it shouldn't need any resets (watchdog timers will enable you to detect if the code is hanging).

This question has a very broad answer. As it depends upon your implementation of both hardware and software.
In very short -
That all depends on your code. The hardware should be able to be left on indefinitely, assuming it is all within spec's. Assuming that, then the biggest concern is the code running on it. Where largest problem of concern is running out of resources. Such as memory. If your code as a memory leak then it will be a problem. Or if there is a bug in the code that can cause it to get stuck. The later can be addressed by employing the WatchDog, which will reset (loose all data) if the code gets unexpectedly stuck.