message:
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

body: Try `AT+CSTT="TATA.DOCOMO.INTERNET"`


sender: user

sender: assistant

body:
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


body:
**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`.


body:
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.


message:
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.**

  1. 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
  2. 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)
  3. 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.

body:
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.


body:
    #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.


message:
Why does this button have a connection to ground?

I am testing this basic [button example ][1] 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?

![Button][2]

  [1]: http://arduino.cc/en/tutorial/button
  [2]: https://i.stack.imgur.com/d93mf.png

body:
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)`


body:
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.


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


message:
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.

body:
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][1]**.

From the product page, I found this image:

> ![][2]

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][3], 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).

  [1]: http://en.wikipedia.org/wiki/Ohm's_law
  [2]: https://i.stack.imgur.com/PbZP7.png
  [3]: http://www.dccwiki.com/images/f/fb/Ohm's_law_triangle.svg


message:
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?

body:
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


message:
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?

body:
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][1]

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.

  [1]: http://www.mouser.com/ds/2/405/sbas020d-114025.pdf


body:
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.


message:
Can the nRF24L01+ CE and CSN pins be attached to Arduino pins A0 and A1?

This [documentation][1] states that the CE and CSN pins can be specified.  Can I specify A0 and A1 as these pins?

  [1]: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01

body:
Yes, you can. The [mirf library](https://github.com/aaronds/arduino-nrf24l01/blob/master/Mirf/Mirf.cpp#L85-86) 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).


message:
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?

body:
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.


message:
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.

1. Timer 1 on pin 5 - Count pulses from car's ECU to calculate speed.
2. Int0 on pin 2 - Read ignition pulse to calculate RPM.
3. 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;
          v = v/10;
          tens = v;
          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;
          v = v/10;
          tens = v;
          v = v/10;
          hundreds = v;
          v = v/10;
          thousands = v;

          //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.

body:
    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**.


body:
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.


message:
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][1], [schematic][2]) for an [MPU 6050][3].

I am currently trying to get the DMP Version of [the examples from Mr Rowberg][4] 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.

  [1]: http://www.amazon.de/Arduino-GY-521-MPU-6050-gyroscope-accelerometer/dp/B00AZH43JC
  [2]: http://playground.arduino.cc/uploads/Main/MPU6050-V1-SCH.jpg
  [3]: http://playground.arduino.cc/Main/MPU-6050
  [4]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050

body:
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?


body:
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][1],
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][2] 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][4].
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][3] 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][5] 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)][6] [(b)][7] [(c)][8] 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.)

  [1]: http://www.invensense.com/mems/gyro/documents/PS-MPU-6000A-00v3.4.pdf
  [2]: http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf
  [3]: http://arduino.cc/en/Main/arduinoBoardLeonardo
  [4]: http://playground.arduino.cc/Main/MPU-6050
  [5]: http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter
  [6]: http://www.adafruit.com/product/757
  [7]: https://www.sparkfun.com/products/12009
  [8]: https://www.sparkfun.com/products/11771


body:
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][1] [schematic][2] 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()][3]" 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.

  [1]: http://arduino.cc/en/Main/ArduinoBoardPro
  [2]: http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf
  [3]: http://arduino.cc/en/Reference/AttachInterrupt


body:
<!-- language-all: lang-C++ -->

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>


message:
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:

1. Setting the prescaler to 1 and the CTC to 1024
2. Setting the prescaler to 8 and the CTC to 128
3. ...
4. 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

body:
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!)


body:
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:

[![Timers and prescalers][1]][1]

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.

  [1]: https://i.stack.imgur.com/9dz8M.png


message:
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?

body:
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.


message:
Reading many analog signals in arduino

I need to measure around **50 - 100 analog sensors** (resistors). This poses two challenges:

1. 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](http://tronixstuff.com/2013/08/05/part-review-74hc4067-16-channel-analog-multiplexerdemultiplexer/). **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.

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?

body:
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.


body:
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](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/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](http://tronixstuff.com/2013/08/05/part-review-74hc4067-16-channel-analog-multiplexerdemultiplexer/).  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.
![resistor mux pdf][2]

In Figures 1 and 2 above, **Rx** is a typical unknown resistance, and **Rs** is a known standard resistor.  Both figures represent *[voltage divider](https://en.wikipedia.org/wiki/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](http://forum.arduino.cc/index.php?topic=65134.0),[2](https://electronics.stackexchange.com/questions/67171/input-impedance-of-arduino-uno-analog-pins),[3](https://electronics.stackexchange.com/questions/36394/arduino-analog-input-example-clarification)) 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()`](http://arduino.cc/en/Reference/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](https://oshpark.com/) or [Seeedstudio](http://www.seeedstudio.com/service/index.php?r=pcb).
![Geeetech CD74HC4067 Analog Digital MUX Breakout Board][3]

  [2]: https://i.stack.imgur.com/HagJE.jpg
  [3]: https://i.stack.imgur.com/7F9en.jpg


message:
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][1] 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?

  [1]: http://www.pjrc.com/teensy/td_libs_OneWire.html

body:
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.


body:
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.


message:
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);
    }

body:
<a href="http://arduino.cc/en/reference/map">`map()`</a>

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


message:
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.
        }
      }
    }

body:
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.


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


message:
Is setup and loop provided for convenience?

Arduino sketches usually feature a [`setup`](http://arduino.cc/en/Reference/Setup) and [`loop`](http://arduino.cc/en/Reference/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?

body:
Those pieces of code are pretty much the same.

If you look at the [Arduino source code](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp#L43-L48) 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.


body:
> 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.


body:
> 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 `.cpp`files; 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).


body:
> 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.


message:
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?

body:
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


message:
Arduino + simple DC motors? (4WD kit)

I am trying to connect 4 small DC motors to Arduino, like those in the following image:
![my kit, 4WD, with 4 simple motors][1]

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! :-)

  [1]: https://i.stack.imgur.com/3wWMY.jpg

body:
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.


message:
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:

1. 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?

2. 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...

body:
1.

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

    No host support here, sorry.

2. 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.


message:
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?

body:
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.


message:
Unable to terminate "void loop"

I have loaded an example sketch that came with the installation of the Arduino software onto my Uno.

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

    void loop() {

      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(1);
    }

From this time TX light is continuously on. It's remaining on even after resetting it. How do I end `void loop` so that TX light goes off.

body:
The TX LED is on, because this sketch is periodically printing the value of the analog pin 0 onto the serial port. The LED seems to be constantly on, because the delay between two `Serial.println()` calls is only approx. 1 ms.

If you replace the 1 with 1000 for example, the TX LED should flash once per second. Start the serial monitor in your Arduino IDE too see the transmitted analog values. Delete the `Serial.` calls to remove the serial port functionality altogether.

You might want to read the documentation of the [loop()](http://arduino.cc/en/pmwiki.php?n=Reference/Loop) and the [delay()](http://arduino.cc/en/pmwiki.php?n=Reference/Delay) functions.


body:
The implied question is how to turn off the Tx LED, which has already been answered and is probably the answer you're looking for. But the question you asked is how to end the `loop()` function. Not to be pedantic but to clarify the use of `loop`, the simple answer is, "you can't". `loop()` is called from a forever loop in the C/C++ main program, function `main()`, so returning from it, either with a `return` statement or by reaching the final close `}` causes `loop()` to be called again. This is intentional as the `main()` function in an embedded system is never supposed to return, thus it must keep re-running the application program.

Update (since this question just reappeared on the front page, I'll add the following to my answer):

`loop()` reads and prints continuously. If you had wanted that code to be executed only once, you could put in `setup()` and leave `loop()` empty. Then the sketch would initialize the serial output, read an analog value, print it - once - followed by entering the empty `loop()` and remaining there until power-down.

A way to execute the loop function once is to write an infinite loop at the end of it, so `loop()` would never return and thus never be re-executed:

    void loop() {

      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(1);

      while(1)
         ;
    }


body:
Seeing as questions about turning off the LED, and the nature of exiting `loop` have been answered, I'll also answer the question they both seem to lead to:

If the overall intention is to "turn off" the MCU, outside of turning off the power supply, it can be put into [sleep mode](http://playground.arduino.cc/Learning/ArduinoSleepCode).

Depending on how you configure the MCU before entering sleep mode, it can even be allowed to wake up on further USART communication.


body: Don't write code in the loop() that should be executed only a few times. Or use a counter. Or an external button. For the permanent light, increase the delay between calls.


message:
Is it possible to extend the reach of a PN532 NFC/RFID shield?

I am working off an Arduino Uno with an [AdaFruit PN532 NFC/RFID shield][1]. The goal is to have a shoe box, with a false bottom. Under that false bottom would be my prototype, which I hope will be able to detect any MIFARE tag that is in the box, above the false bottom.

The range obviously for these devices is practically touching, but I was was wondering if there is anyway to extend the reach of the NFC/RFID shield, so that the entire false bottom of the box could act as that antenna.

  [1]: http://www.adafruit.com/products/364

body: I suspect not. NFC is designed for short range for privacy reasons. Some RFID systems have longer ranges (a few meters). They work by using an electromagnet to create a switching magnetic field. The RFID/NFC chip takes power from the magnetic field and then modulates a signal onto it, which the sensor detects. In order for it to work the chip needs to be close enough to get as strong enough field to power itself, and to modulate that field.


message:
Fade in UV lights connected to mains

I have a PIR motion sensor and would like some ultra bright UV led lights to fade in when this is triggered. It is one unit, consisting of 225 led lights connected to 240v mains (Australia). I bought a relay for the basic on/off function but was wondering if fading on and off can be done relatively easily - this is my first arduino project. I would value any suggestions.

body:
Most LED lights can't be dimmed from the mains supply.

In order to dim LEDs you have 2 choices: Limit the current through each LED or series string of LEDs, or pulse them very rapidly with a varying ratio of on/off times (known as a variable "duty cycle")

It's usually easiest to pulse them. To do that you need to be able to control the flow of DC to the LED array. If you were to take apart your IR array you would very likely find an AC to DC power supply that then feeds the LEDs through current limiting resistors.

If you can figure out the voltage and current that comes out of the DC power supply, you can select a power transistor (almost certainly a logic level power MOSFET) to wire in as an electronic switch that enables you to pulse the power to the LEDs using a logic signal from your Arduino.

This is actually a lot simpler than it sounds. You would cut 1 wire inside your LED array, solder in a single transistor to the 2 ends of the cut wire, and run the third wire from the transistor out to your Arduino.

Arduinos have several I/O lines that can be configured for PWM (Pulse Width Modulation) which is designed for this very purpose. You'd connect a PWM line to the gate of a logic level power MOSFET, and then send it a signal from 0 to 255, which would effectively dim the LED array in 255 brightness steps.

There are beginner sample projects that let you dim single visible light LEDs using this very approach. (For a single LED you don't need a transistor though, so they are really easy to wire up. All you need is a current limiting resistor.) I suggest you find and build one of those projects to get a feel for how (and how well) it works.


message:
Arduino starter kit example LEDS modification

I just begun with the Arduino starter kit, and in the second example I would like to test some changes to learn more.

The point is to have a green LED shining, and when pressing the button the two red LEDs blink.

This is the code:

    int switchState = 0;

    void setup()
    {
      pinMode(2, INPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);

      // the button is pressed
      digitalWrite(3, LOW);

      digitalWrite(4, LOW);
      digitalWrite(5, HIGH);
      delay(250); // wait for a quarter second
      // toggle the LEDs
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      delay(250); // wait fo a quarter second
    }

    void loop()
    {
      switchState = digitalRead(2);
      // this is a comment
      if(switchState == LOW)
      {
        // the button is not pressed
        digitalWrite(3, HIGH); // green LED
        digitalWrite(4, LOW); // red LED
        digitalWrite(5, LOW); // red LED
      }
      else
      {
        // the button is pressed
        digitalWrite(3, LOW);

        digitalWrite(4, LOW);
        digitalWrite(5, HIGH);
        delay(250); // wait for a quarter second
        // toggle the LEDs
        digitalWrite(4, HIGH);
        digitalWrite(5, LOW);
        delay(250); // wait fo a quarter second
      }
    } // go back to the beginning of the loop

I added a modification into the schema (a fourth LED in parallel with the green), like this:

![enter image description here][1]

![enter image description here][2]

But the added LED is not shining. It's a long time ago I finish school and I forgot a lot of things. Am I wiring the fourth LED incorrectly?

  [1]: https://i.stack.imgur.com/1jCas.jpg
  [2]: https://i.stack.imgur.com/ZcS7d.jpg

body: Blue LEDs have a higher Vf than green LEDs, hence much less current will pass through it, not enough to make it visible. Give it its own resistor instead of sharing the resistor with the green.


message:
Serial.println(): Where is the text printed?

When I used `Serial.println()` in the code I naively believed I would see the characters that I sent displayed on that little black area just under the interface (just like a terminal).

    #include <Servo.h>

    int moveServo;

    Servo myservo;

    void setup()
    {
      myservo.attach(0);
      Serial.println("      Hello Earth");
      Serial.println();
    }

    void loop() {
    }

Can someone tell me just where `Hello Earth` would be displayed?

body:
The IDE on your computer has a menu item under the tools menu called "Serial Monitor." On my Mac, at least, it is indeed a black area under the source editor for the current sketch.

It won't work unless you call the `Serial.begin()` function in your setup method before the first `Serial.print()/println()/write()` function call.

Something like this:

    //Set up the serial port @ 9600 baud for display back to the computer
    Serial.begin(9600);
    delay(25);
    Serial.println("Hello world!":);


body:
You can open the serial console in the Arduino IDE by pressing ctrl-shift-M (as in Monitor) or selecting it in the menu.

Also, to use the serial interface, you have to initialize it using `Serial.begin(9600);` in `setup()` before calling any other function which writes to it. You can use any other baud rate - but this is the default in the Arduino IDE, if you change it, you should change it in the IDE too.


message:
Serial.begin(): Why not always use 28800?

In a lot of the sample code online people add the line `Serial.begin(9600)` in the setup block.

When I look up what `Serial.begin()` is on the official documentation, it says that it controls the bit per second data transfer.

So the obvious question is, why not use 28800, the highest transfer rate? Why do people settle for 9600? What is the limitation here?

body: I think the main reason people use 9600 most of the time is that it's the default baud rate in the Arduino IDE. Also, faster data rates could also be unreliable if the serial signal has to travel a long way - although I have no idea why this was selected as an optimum speed.


body: I think it is a kind of tradition to use a transfer rate that is not the slowest one (300) but also not one that could eventually cause problems in some setups (28800 or even 115200). The PC serial port (most often a FTDI232 USB adapter) can cope with higher rates but your DIY hardware may not. So 9600 bps has established itself as some kind of standard transfer rate for code examples.


body:
> Why do people settle?

People settle because it is more than fast enough.  The most common use is just to print some stuff on a terminal for debuggin.  9600 baud is 960 characters per second, or 12 x 80 character lines per second.  How fast can you read? :)

If your program is using the serial port for bulk data transfer, you would choose not to settle.

> What is the limitation...

The limits on serial are high.  Directly you can use 115200 baud in your programs and it will just work.  The Arduino terminal will allow a max of 115200, but other programs such as RealTerm would let you run higher.

Hardware serial will run to 1 M baud.  If you read around you will see people have used up to 1 M by directly controlling the UART.  You might get benefit of high baud rates for uses such as transmitting via a bluetooth chip.  If you are using the hardware serial interface to exchange from chip to chip with just a short distance, then 1 M baud is completely feasible.  Think of all the SPI and I2C devices that operate just fine at 1 MHz clock rate.

Over larger distances, you will start to have problems with noise when using logic level (plain 0 to 5V) signalling.  To use larger distances, you would add a transceiver to provide robust signalling, commonly RS-232 and less commonly RS-485.  With RS-232 you could run a mega bit at distances of 10's of feet.

The microprocessor clock speed will be the real limit.  With a hardware UART, the processor must load one byte to the UART every 10 bits (for N81).  So when you get to 1 M baud it will be a challenge for the 16 MHz processor to keep the UART supplied with data.  A new byte will be sent every 160 clock ticks, which is very few lines of code.  For a short burst of data, you might achieve that rate.  The message is, the processor will run out of speed before the UART is the limit.

Note, this all applies to **HardwareSerial**, software serial is very different.


body:
Back in the mists of time, the "gold standard" for remote keyboards (using a a telephone modem, and teletypes, if you remember those) was 9600 baud, initially achievable only over a dedicated phone line. Time moves on, slowly; technology advances, rapidly; and memory moves even more slowly than time (it seems). We can routinely communicate, at least over a several meters, at a couple of orders of magnitude faster than 9600 baud. What was once considered a gold standard is no longer gold, but still thought of as standard.

tl;dr: It's history, not technology.


body:
In addition to all the interesting answers, it worth mentioning that setting the serial speed to _XXX_ bits/s does not necessary imply _XXX_ bits/s on the hardware.

Clocks -- even quartz based -- are imperfect and subject to drift. In addition, as the serial clock is usually generated through a power-of-two pre-divisor and (integer) counter, all value cannot be accurately obtained given a base clock frequency. With the help of the start/stop bits, asynchronous serial communication may be tolerant to some clock drift. But this has limits.

For example, if your ATmega328PA is running at 1MHz, you can achieve 9600b/s at 0.2% of error. But at 14400b/s the error is -3.5% (actually communicating at 13900b/s). And at 28800b/s, the error is +8.5% (actually communicating at 31200b/s). All those figures are from _ATmega48PA-88PA-168PA-328PA datasheet, p200_.

This is _not_ an issue when two identical devices communicate together (as there are in fact communicating at the _same_ speed). It _might_ be an issue when communicating between different devices.

Increasing the base frequency does not necessary improve significantly the accuracy. For example, running the same ATmega328PA as above at 2MHz does not really give better results as those are mostly due to rounding errors. But running it 1.8432MHz give very accurate bps from 2400b/s up to 57.6kHz.


message:
What is commonly done to stop a servo after reaching desired position?

When I started Arduino, I did not expect that everything must be contained in an infinite loop. I thought I could just write something like: motor start -> motor stop. But in actuality, what I get is motor start -> motor stop -> motor start -> ... forever and ever.

What is commonly done to stop a servo after it is in a desired position? Do I use `servo.write(desired position)` to keep it from turning? Do I detach the output wire?

What are some of the risks involved?

body:
A normal servo doesn't have a "go" function, it only has positional control. That is, whether you run `servo.write(90)` forever or once, the servo will go to 90 and continue to actively keep that position until you write another position. The only way to turn a servo  off is:

    servo.detach();

For a normal DC motor, you will need to turn it on then off and then have kind of state tracking in the loop to never turn it on again, using a variable or `millis()` etc.

Of course, if you want something to only run once, put it in `setup()` (maybe within a loop in setup for simple tasks).

Also, you can simulate ending the program by entering an infinite loop with `while(true){}` or `for(;;){}`.


body:
You do not "stop" a servo.

A servo is always running.  In a general sense, the servo is a control loop that takes as input a position target and applies force to hold at the requested target.  If you want the target to be maintained, then the servo must be running.

A servo motor contains electronics that are internally turning a DC motor on and off as necessary to hold the target position.  If the target does not match the current position, it turns on the motor to turn until the two match.  Once the output shaft reaches what you requested, the electronics inside the servo motor turn the motor "off".  Off meaning the DC motor is drawing little or no current.  The servo control loop is always running comparing the shaft position to a target.

If you powered off the entire servo motor, the position is not under control and could move.  For many applications if you unplugged the wires, the gears and motors apply enough friction that it would not turn.  But in general, you do not count on friction to make things work.

    Do I use...Servo.Write(desired position) to keep it from turning?

Yes.  To tell a servo to stay at one position, you can just keep sending it the same target.

But you do not have to Write() again and again.  If you want, you can keep track of what the last setting was and apply only when you have a change.   For example, you can code like this:

    if(position_target != position_last_set) {
      Servo.Write(position_target);
      position_last_set = position_target;
    }

Regardless of your code, under the hood, Servo is constantly transmitting the position target to the servo motor.


body:
I had the same problem.

I figured out that simply adding `myservo.write(90); delay(4000);` helps to stop motor.

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
                    // twelve servo objects can be created on most boards

    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()

    {
      myservo.write(180);
        delay(8000); ////stops motor for 8 seconds
      for(pos = 180; pos>=90; 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

      }

        myservo.write(90);
        delay(4000); //stops motor for 4 seconds
      for(pos = 90; 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

      }

    }


body: A servo, by nature, is used to hold a position in the presence of disturbances trying to disturb that position. If you just need to move a mechanism that won't try to (or can't) back-drive the motor, your application ay be better served by a geared motor with a shaft encoder or position switches.


body:
This is a very brief explanation regarding servos.

The type of servo system that you are proposing is a none positional open loop system and is generaly used for accurate movement rate (controlled speed) . The loop in this case is usually a tachogenerator which sends a voltage (which is proportional to the motor speed) to a comparator which compares the tachogenerator voltage to the required adjustable voltage , the output of the comparator then regulates the motor speed, hence the required speed . this type of servo system will continue to run at the constant speed until  A the comparator signal is set to zero or B the motive power is reremoved from the moter ( switched off)   ----Point to point servo control , on the other hand ,, generally uses a position command which is verified with a signal from an encoder at which point the servo will stop until another command is issued from the stack ( EG. another position location or a dwell command (wait) or other )  the most common way to do this is to use gcode which has the ability to give full control of your servo system . If there is no encoding device then accurate servo position control is very difficult if not impossible.


body:
`myservo.detach();` is what you are looking for. Moving it to a location than detaching. This is good when you want to use it to control a servo and not have it continue to take power like when using a battery.  Here is a example.

    #include <Servo.h>
    Servo myservo;  // create servo object to control a servo

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

    void loop() {
      myservo.attach(9);
      // attaches the servo on pin 9 to the servo object
      delay(15);
      myservo.write(1);
      // sets the servo position according to the scaled value
      delay(1000);
      // waits for it to get to the position
      myservo.detach();
      delay(1000);
      myservo.attach(9);
      // attaches the servo on pin 9 to the servo object
      delay(15);
      myservo.write(179);
      // sets the servo position according to the scaled value
      delay(1000); // waits for it to get to the position
      myservo.detach();
      delay(1000);


body:
The word _servo_ has a vague definition and can encompass many types of subcomponents. If you want **no-power position holding** using an electromagnetic motor, then there are four options:

* High viscosity grease
* Dash pot
* Very high gear ratio
* magnetic brake shoe / brake band

EDIT: There are some additional possibilities, but it's sort of an effect of some motor designs:

* Permanent magnet pole holding torque, or detent torque
* Permanent magnet drag torque

The high viscosity grease and dash pot have similar functions; providing a high static friction to resist motion, which then breaks away into movement. (A dash pot is essentially a toothed gear inside a toothed wall container, and which is permanently filled with a high viscosity fluid.)

However both of these will add to the motor load, and when they get hot they tend to become thin and runny and lose holding ability.

A high gear ratio increases the torque required to back-spin the motor. Though note, if any gearbox could have a perfectly frictionless lubricant, no amount of gear reduction could stop back-spinning.

So really this is similar to the thick grease and dash pot, but gear reduction allows just the normal thin lubrication to have enough static breakaway friction, to stop back-spinning.

A magnetic brake gives you active control over the static breakaway friction, and can allow for very high holding ability vs intermittent load spikes on the output shaft. Typically with the power off, a spring engages the brake to hold position with no power.

Note, there are two different kinds of braking: static position holding, and deceleration of a moving mechanism.

The second type both dumps heat into the brake pads and friction plate, and wears down the pads and friction plate. If the brake overheats, the pads usually disintegrate, and the brake now won't hold position.

Unless we're talking about large machinery, usually servo brakes are simple designs without replaceable parts. When the brake fails, you pull the whole thing off and replace it ... including possibly the entire servomotor and gearbox too.

For long service life with magnetic braking, you need to actively decelerate the load using the servo, and then once it has stopped moving, then engage the brake to just do the job of holding position.

Using a magnetic brake for no-power static load holding only, will look like this:

  * Power up motor, get current position, and begin actively holding position.
  * Energize brake to release it
  * Accelerate and move to new position
  * Decelerate motor and hold end position
  * Remove power from brake to engage it
  * Turn off power to motor

The motor is powered up and goes into position holding first, so that the load doesn't suddenly slip in either direction, in the instant between the brake being released and the servomotor then becoming active.

**EDIT #1**: For some permanent magnet motors, even with the power off there is a resistance to rotation because in certain positions, the magnets and the pole pieces more closely attract to each other, known as *detent torque*.

This pole positioning is like a low-energy valley and it takes a bit of force to overcome the magnetic attraction and move the rotor in either direction using an external torque.

You can feel this in some brushless fans and stepper motors, where if you rotate the shaft unpowered, it resists continuous motion, and there seem to be high resistance points that the rotor does not want to cross. When spun, the rotor rapidly slows, and may fall into a back-forth oscillation as it settles into one of the magnetic attractive wells.

This can be used to resist external torques without a brake, but making use if it requires stopping the rotor in one of the magnetic wells rather than a specific position you may want. But if combined with a gearbox, the exact specific stopping position may not matter too critically, and there may be a number of wells next to each other where the rotor can stop that provide an acceptable end-effector alignment.

**EDIT #2**: Permanent magnet drag torque is an effect of shorting all the power wires together. When this is done it takes considerably more force to rotate the shaft than with the stepper coil wires disconnected from each other.

This is because with the coil wires all connected together, when the rotor turns it acts as a generator and current flows through the coils. This current flow creates what is known as counter electromotive force (CEMF), which counters the magnetic field of the permanent magnet.

This CEMF can provide additional resistance against rotation when the servo is unpowered. Although CEMF won't prevent motion, it can help resist continued motion and provide instant deceleration when intermittent load spikes are applied that try to move the unpowered servo.

All of the above is also generally true for linear motor servos. Those don't have gear reduction, but the motion carriage can be lubed with thick grease, be equipped with a dash pot, and have position holding magnetic brakes.


message:
Why does my Arduino seem to reboot every time that I open Serial Monitor?

Every time that I open the Serial Monitor, my [Arduino Uno][1], seems to go back to `void setup()`. Is it a normal thing?

  [1]: http://arduino.cc/en/Main/ArduinoBoardUno

body:
That is a normal feature of Arduinos, not an error. I find it mildly annoying sometimes, but it's nice for interactive programs that want some kind of menu message to be the first thing you see in the terminal.

If you want help disabling the auto reset, your options are detailed in *[Disabling Auto Reset On Serial Connection][1]*.

  [1]: http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection


message:
Curious: What would happen if you connect 5V and GND port directly with a wire

Has anyone ever accidentally or inadvertently connected connected the supply port with the ground port with a wire?

Does Arduino provide internal safety to prevent the circuit board from shorting out?

body:
There is some protection.

When powered from the USB port, the UNO has a 0.5 A fuse.  This is a self resetting fuse that will trip when the current is high, and reset when it cools back down.  These fuses are great for peripherals that might be exposed to occasional "oops".  See the [data sheet][1] for more details of the part on the UNO.

When powered from the PWRIN plug, the voltage regulator provides some protection.  The device on the UNO contains over current and over temperature protection, which is common for regulators such as this.  The device will get very hot, and the protection will activate to limit the current (see [datasheet][2] for details).  By design, the regulator chip should protect itself from being destroyed.

So to first order, if you by mistake connect the +5 on the header to GND, all that will happen is Vcc will be reduced to near zero Volts.

The caveat is that a small spark can be generated when you make this short to ground, especially if you have a bunch of capacitors on Vcc.  That spark may cause a voltage transient that could damage a pin.

  [1]: https://www.bourns.com/pdfs/mfmsmf.pdf
  [2]: http://www.onsemi.com/pub_link/Collateral/NCP1117-D.PDF


message:
Keyboard Control Not Working As Intended

I'm trying to control a single motor.

If I press 'a', then motor 1 should turn to 0, if I press 's', then motor 1 should turn to 180

    #include <Servo.h>

    char key = 0;
    const unsigned int BAUD_RATE = 9600;

    Servo Servo_0;

    void setup()
    {

      Servo_0.attach(0);
      Servo_0.write(0);

      Serial.begin(BAUD_RATE);

     // Serial.println("      Arduino Serial Servo Control");
     // Serial.println("Press < or > to move, spacebar to center");
     // Serial.println();

    }

    /*
    a - 97
    s - 115
    d - 100
    f - 102
    */

    void loop() {

      if(Serial.available()>0)
      {
          key = Serial.read();
          Serial.print("I received: ");
          Serial.println(key, DEC);

         if(key == byte(97))
         {

           Serial.print("Turning Motor 1 to 0 deg");
           Servo_0.write(0);

         }
         else if(key==byte(115))
         {
           Serial.print("Turning Motor 1 to 180 deg");
           Servo_0.write(180);

         }

         delay(1000);
    }

But what is happening is that the motors are barely turning after I enter the key onto the Arduino monitor interface. Can anyone diagnose as to what might be happening?

body:
The problem I see is that your servo is attached to pin 0.

Pins 0 and 1 are used by arduino unos and megas for serial communication, so you can't output to a motor and send/receive serial at the same time. Try moving the servo to pin 3 and see what happens.

In response to your comment, any character sent from any terminal (or other piece of hardware) will work; you do not need to use Processing to communicate with an arduino.


message:
Building a gps system

I'd like to build a simple GPS system. It should be very little. For the software side, I will build an API, so from my PC/smartphone/whatever else I could ask the GPS system where it is located (I think Google provides this kind of feature).

How can I do this? My main problem is the GPS and the its building. I'd like to build the smallest thing possible, because I have to hide it. My idea is to hide this GPS system in my bike: I'd like to locate my bike if someone stole it. As you can see, internet is a problem.

I'm not asking to design anything. I would only know what I need to build a basic GPS system that has just the feature described. What do I need? Is it possible to do it? Does GPS require Internet connection? I would know if I could make it or not without internet access.

body:
***"Is it possible to do it?"***

Well... everything is possible :-)

***"Does GPS require Internet connection?"***

GPS doesn't require internet. A GPS receiver (e.g. http://www.modulestek.com/prodts/GPS/Mars740-mini/Mars740-mini_SPEC.pdf) is connected to the reading unit via USB or a RS232 interface. The protocol is very simple. However it only provides latitude and longitude. If you want to have an address, map data is required (for *this* you would need internet - or a large memory).

And of course such a system requires good signals from the GPS satellites.

***"What do I need?"***

First you need a GPS receiver (see above).

Second, you need a microcontroller unit which runs your application and does all the control of the external units.

Third, you need a GSM module (e.g. http://www.exp-tech.de/Shields/Wireless/GSM-GPRS/adafruit-fona-mini-cellular-gsm-breakout-sma.html) to send a message.
Don't forget the antenna for connection to the mobile communication network.

Fourth, you need a power supply. Ideally it has a battery which can be reloaded when driving.

As you may see, if you put all this together you are far from the "smallest thing possible".

Actually any modern smartphone could be enough. Mount it "invisible" under your saddle, connect it to a bike charger, find the proper App and that's it - although it might not be the smallest solution.

I don't know any, but I'm sure there *are* products off the shelf that fulfil your requirements, designed and developed by experienced engineers, and thus smaller and maybe cheaper than what you ever could achieve on your own.


message:
Arduino Uno 3: Stuck at 'uploading...' sketches

I was playing around with my Arduino Uno R3 board with Sublime Text 2 & 'Stino' as IDE

I am not sure if it is my code is the problem or if I broke something...

I pressed upload while another sketch didn't finish uploading, even the original Arduino IDE can't upload new sketches anymore!

This is my code:

    // singleServo.ino

    #include <Servo.h>

    Servo servo;
    const int button = 2;
    const int led = 13;
    const int buzzerPin = 10;
    const int duration = 180;

    int stateLED = LOW;
    int previous = LOW;

    void setup() {
     pinMode(led, OUTPUT);
     pinMode(button, INPUT);
     pinMode(buzzerPin, OUTPUT);
     Serial.begin(9600);
    }

    void loop() {
     int stateButton;

     stateButton = digitalRead(button);

     if (stateButton == LOW && previous == LOW) {
      if (stateLED == HIGH)
      {
       stateLED = LOW;
       initAction(duration);
      }
      else
      {
       stateLED = HIGH;
      }
     }

     digitalWrite(led, stateLED);
     previous = stateButton;
     servo.detach();
    }

    void initAction(int time_iA){
     tone(buzzerPin, 523, 200);
     delay(200);

     shiftServo(180, time_iA);

     tone(buzzerPin, 262, 200);
    }

    void shiftServo(int angle, int time_sS) {
     servo.attach(9);
     delay(500);
     int position;

     for(position=0; position <= angle; position += 1)
     {
      servo.write(position);
      delay(time_sS / 180);
      Serial.println(servo.read());
     }
     // for(position=angle; position >= 0; position -= 1)
     // {
     //  servo.write(position);
     //  delay(time_sS / 90);
     // }
    }

I am a newbie with all things Arduino - Please help!

EDIT:
After rebooting the system (Ubuntu Linux 14.04) everything was working just fine again!
But I'm going to take the serial functions out too.

body:
You have to wait for the first and all other uploads to fail.

If you are not sure, a reboot is the most reliable solution.

Also note that if your sketch sends a lot of data over serial, a manual reset of the board may be needed.


body:
I've got the same problem on my Ubuntu.
Eventually, I was stuck at every uploading, even after unplugging+replugging the device.

Killing all avrdude process, remove the problem.

    sudo killall avrdude

or with new IDEs:

    sudo killall avrdude_bin


body:
I had this happen to me on an UNO R3. I solved the issue by disabling Bluetooth on my laptop. It was causing a conflict on COM5.

I had ruled out the board, cable, and IDE. Finally noticed in Device Manager that COM5 had entries (one being the Arduino and the other being Bluetooth)

Hope that helps someone else that might have this issue in the future.


body:
I had the same problem with arduino uno r3 on win10.
 The solution was simple:
1. open the task manager (Ctrl + Shift + Esc)
2. stop all open COM processes
 and the arduino upload worked again.