body:
In case someone does ask the same question in the future, this is the explanation for the USB/XBee switch functionality on the XBee Pro Shield V3 [![XBee Pro Shield V3][1]][1]

The switch serves to connect/disconnect the XBee Pro shield v3 to the Hardware TX->1 & RX<-0 Lines of the Arduino. Moving the switch to the USB side, allows you to disconnect the XBee Pro shield v3 from the hardware serial lines and upload code to your Arduino. If the switch is on the XBee side, this allows your XBee Pro shield v3 to use the TX->1 and RX<-0 lines of the Arduino and if you want to upload code to your Arduino, you would have to remove the shield otherwise it would result in an error trying to upload code. [![Arduino Uploading Error][2]][2]

  [1]: https://i.stack.imgur.com/aT7El.jpg
  [2]: https://i.stack.imgur.com/IRpBe.png


sender: user

message:
What is the function of the XBee / USB switch on an XBee shield?

I recently bought an XBee shield ([this][1]). The shield has a switch that seems to switch between USB/XBee. However, there is no USB port. What exactly is the switch supposed to do?

  [1]: http://www.ebay.com/itm/New-For-Arduino-ZigBee-XBee-Bluetooth-Bee-V03-Shield-Module-Wireless-Control-Hot/301457628487?_trksid=p2047675.c100005.m1851&_trkparms=aid=222007&algo=SIC.MBE&ao=1&asc=30543&meid=6648f5c1a8f54e9e92e799f4092616ce&pid=100005&rk=3&rkt=6&sd=221568487830&rt=nc

sender: assistant

body:
The Xbee shield has aswitch labled Xbee/USB. This determines how the Xbee's serial communication connects to the serial communication between the microcontroller (ATmega8 or ATmega168 or Atmega328) and FTDI USB-toserial chip on the Arduino board.

In the Xbee position the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI
chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer.

In the USB position, the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer -
however, **IMPORTANT** this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module.

THANKS TO RS-COMPONENTS FOR THE DETAILS!!!!!


message:
Arduino at 20 MHz?

I wonder why Arduino doesn't run at 20 MHz, the frequency the AVR is specified for. Now, running at 16 MHz, we're wasting 20% performance for nothing.

I don't think there are *any* implications when you replace the 16 MHz resonator with a 20 MHz type, with probably the sole exception for the baudrate in the bootloader. Or is there?

Does anybody know why the Arduino designers chose 16 MHz?

body:
There's no hardware reason (as far as I'm aware) that you couldn't run a suitable Arduino at 20 MHz. You'd run into minor timing inaccuracies in software though, as the standard Arduino configuration apparently works best if the clock speed is either 8 or 16MHz.

I suspect this is largely for historical reasons. Early Arduino boards were based on chips which only went up to 16 MHz, such as the `ATmega8`. Using the same configuration for all chips just keeps everything a bit simpler and more consistent.

There is more information here about the timing issues: http://forum.arduino.cc/index.php?topic=158223.0#msg_1186708


body:
You can, and I do.

It's not technically an Arduino anymore, I guess. I made my own board, replacing a resonator on a board will require some fine soldering, but it is definitely possible.

There are some gotchas: Anything time-related (e.g. millis() ) will be run faster than is should - 25% more millis() per second. Also, the bootloader expects 16mhz, so you won't be able to reprogram it at this speed. I purchased a USBASP programmer - it hooks into the 2x3 pin grid on one side of the board, and lets you reprogram it without the bootloader (this is how the bootloader is put on in the first place!). You will need at least 4.5 volts at 20mhz to avoid problems, compared to 3.78 volts for 16mhz - this means batteries will drain somewhat quicker (3x1.5v batteries will run down pretty quick), and if you have any motors or other draw on the batteries, 3 1.5v batteries will probably not work even if they are fresh.

Alternatively, going in the exact opposite direction, the lower the clock speed, the less voltage is required - for some projects, you might not need the clock speed - you can go down to 1.8v running at 4mhz.


message:
Arduino Cross Correlation?

How can I write lightweight cross correlation code for arduino? I couldnt find any solution. The measurement system contains an ultrasonic sensor and a servo  that turns from 45 to 135 degree and measures distance from 4-300 cm. Than i collect data in an array which contains distances with respect to angle. System makes several measurement like this and program finds cross correlation between new and old arrays.

http://www.instructables.com/id/How-To-Make-an-Obstacle-Avoiding-Arduino-Robot/

body:
Given the time scale of the measurements, performance is not an issue.
And since you are not computing in real-time, as the samples are being
measured, you can apply the definition of cross-correlation as is, and
compute it in a double loop. The only difficulty is figuring out that
cross-correlation may not be the proper tool for the job... and finding
the right one! My assumption is that you want to estimate a rotation
angle between the two measurements.

The mathematical definition of cross-correlation assumes infinite
arrays. In practice, cross-correlation is often used to locate a short
pattern inside a long signal. In this case, the computation is done only
for shifts where the pattern completely overlaps the signal. Then the
length of the result is

    length(result) = length(signal) − length(pattern) + 1

In your case, since your pattern is a previously measured signal, this
would give a single-sample result, which is useless.

You could instead compute the integral for all shifts where there is
_any_ overlap between the pattern and the signal. This is equivalent to
zero-padding the signal. This has the drawback of biasing the result: if
your signal and pattern are both featureless (positive constants), you
will find a very nice peak at zero shift!

You can remove this bias by subtracting the average from both the signal
and the pattern, and correlating (signal − avg(signal)) with
(pattern − avg(pattern)). This still carries a bias for “big”
features. Imagine for example that, after removing the averages, you
have

    pattern = [  0,   0, −20, +20,   0,   0];
    signal  = [−50, +50,   0,   0, −20, +20];

You would expect your correlator to find a good match between the
[−20, +20] of the pattern and the [−20, +20] of the signal. The
correlation is, however, much better with the [−50, +50] of the signal.
You may try to alleviate this by computing a normalized
cross-correlation instead, but you will at best make both matches
equally good.

My suggestion is that you completely forget about correlations and
instead think in terms of “goodness of fit”. Correlations are good for
finding scaled and shifted copies of a pattern inside a signal. You are
looking for _shifted only_ copies, with no scaling. Your question should
be: if you shift the pattern by some amount, how well does it fit the
signal? What amount of shift gives the better fit? The canonical answer
to all “goodness of fit” questions is to minimize the RMS difference
between the two: you compute the sum

    S = Σ(signal − shifted(pattern))²

Then the RMS difference is

    RMS(difference) = √(S/N)

where _N_ is the number of samples involved in the sum. The most likely
shift is the one that minimizes this error. In practice, you do not need
the square root, you just minimize

    RMS(difference)² = Σ(signal − shifted(pattern))² / N

You can implement this formula as-is, it's completely straightforward.
Just beware that _N_ depends on the shift, as it's the length of the
overlap. And avoid going to very small overlaps (i.e. large shifts).

Now, if you expand the square inside the sum, you may find that, after
all, this is not so far from a cross-correlation... And BTW, all this
has nothing to do with Arduino.


message:
Uploading... forever

This is my code:

    const int trigPin = 4;
    const int echoPin = 2;
    const int trigPin2 = 6;
    int incomingByte;
    int val, val2;
    const int echoPin2 = 7;

    void setup() {
      // initialize serial communication:
      Serial.begin(9600);
    }

    void loop() {
      pinMode(trigPin, OUTPUT);
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      pinMode(trigPin2, OUTPUT);
      digitalWrite(trigPin2, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin2, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin2, LOW);

      pinMode(echoPin, INPUT);
      pinMode(echoPin2, INPUT);

      val = digitalRead(echoPin);
      val2 = digitalRead(echoPin2);

      if (val && val2 == HIGH) {
        Serial.println("Elephant on tracks");
      }

      if (Serial.available() > 0) {  // if the data came
        incomingByte = Serial.read();
      }
      // read byte
      if(incomingByte == '0') {
         digitalWrite(trigPin, LOW);
         digitalWrite(trigPin2, LOW);
         Serial.println("The system is OFF.");  // print message
      }
    }

Anyhow, I click upload, and as the title of this question says, have to wait forever.
Not only this code, nothing gets uploaded. It was working just fine a week ago.
I run a Windows 7 64-bit system, and have an Arduino Uno R3.
Does anyone have any suggestions?

body:
*Comment by SR1 turned into an answer*:

Thanks for the suggestions. It finally worked. It was because of my HC-06 Bluetooth module. I don't know if the mistake was mine or if it is a fault with the module.

---

(Done to reduce "unanswered questions" on this site).


body:
From your code, I assume that the bluetooth module is connected to pins 0 & 1 on the arduino. These pins are to be kept free/floating/not connected to anything if you need to upload code to your board.

Use software serial in such cases reduces the headache


message:
arduino ethernet shield

I bought a ethernet shield for my Arduino Uno. I plug it my Arduino and PC with ethernet cable. There is all led is working on ethernet shield. But when i try to examples about ethernet which is in Arduino IDE as "DHCPChatServer" example.

 **I hope to see;
"Trying to get an IP address using DHCP"
"My IP address: 192.168.1.177"**

**But I just see "Trying to get an IP address using DHCP"**

Any problem with my ethernet shield?

body:
When you connect your arduino directly to the PC using the ethernet cable, neither of them have any information about the network.

Most ethernet devices attach to switches, routers, and gateways, and one or more of these devices host network services such as DHCP, DNS, or provide a way to obtain those services.

Without DHCP, for instance, neither your PC nor the Arduino know what IP adress to use, what their netmask is, and whether there's a gateway to other IP addresses.

You have a few options:

 * Follow the [Automatic Private IP Addressing][1] specification, which windows computers default to when no DHCP server is present or available. Set the IP address of the Arduino to 169.254.x.y where x and y are randomly chosen numbers between 0 and 255, and set th netmask to 255.255.0.0.  The windows computer should have done the same if no static IP address was set - use `ipconfig` on the windows command prompt to find its IP address.  Your computer and arduino should be able to talk to each other.
 * Set up a router. It doesn't need to connect to the internet, it just needs to connect to both the PC and the Arduino.  It'll implement a DHCP server and make sure, at minimum, that the two devices can talk to each other and the router.
 * Set static IP addresses on both devices.  Set up the PC with something like 192.168.42.1 with a netmask of 255.255.0.0 and the Arduino with 192.168.42.2 and the same netmask.  Now they should be able to talk to each other.
 * Connect both to an existing network.  The network should already have a router with DHCP on it, so it'll take care of everything, and as a bonus you may be able to get internet access as well, which could help with testing since you can use the ethernet shield to communicate with google and other known working services, rather than trying to set up a server on the PC.

  [1]: https://support.microsoft.com/en-us/kb/220874


message:
Reading/writing to Arduino GPIO pins from raw C code

I'm interested in writing a C program *without* the Arduino IDE and related libraries and am trying to figure out how I can access the GPIO pins for read and write.

My *assumption* is that the GPIO pins are - at the hardware layer - just memory addresses, and so if I know what their address is I can send/receive data to and from them.

* For writing to the digital pins, do I just send an `int` with a value of `0` or `1` to the pin's address? If so, what might that code look like? Can I then assume I could poll that address for a value, which would be either `0` or `1`?
* Can I assume the same for analog pins, but instead of binary values, I'd get an integral value between `0` and `1023`?

And if I'm way off here, and pins are *not* accessed via memory addresses, then how?

Again, the solution I'm looking for wouldn't involve Arduino software, just the Arduino hardware (an AVR or ARM MCU). Bonus points for C pseudo-code examples! Thanks in advance!

body:
In theses cases you are right, using register address is the way to read/write data from/to digital pins.
In the case you use analog input, the process is similar but you have to follow some procedures before getting the value of the data.

**[GPIO REGISTERS][1]**

For AVR micro-controllers these registers are:
DDRn – Data Direction Register
PORTn – Port Output data Register
PINn – Port Input Register
n- Indicates the port name i.e. A, B, C & D
If you have arduino board and want to use these pins, look for mapping pictures about arduino and avr pins.

The following is an example from the Arduino website.

DDRD is the direction register for Port D (Arduino digital pins 0-7). The bits in this register control whether the pins in PORTD are configured as inputs or outputs so, for example:

    DDRD = B11111110; // sets Arduino pins 1 to 7 as outputs, pin 0 as input
    DDRD = DDRD | B11111100; // this is safer as it sets pins 2 to 7 as outputs
                             // without changing the value of pins 0 & 1, which are RX & TX

See the bitwise operators reference pages and The Bitmath Tutorial in the Playground

PORTD is the register for the state of the outputs. For example;

    PORTD = B10101000; // sets digital pins 7,5,3 HIGH

You will only see 5 volts on these pins however if the pins have been set as outputs either by using the `DDRD` register directly or by using the  `pinMode()` function.

**For analog read**

You just need to include the headers and start using the registers. They hold the equivalent hexadecimal values for your microcontroller. And the procedure is described in the datasheet. All you have to do is to translate it to code.

    // this code scans ADC1 for an analog signal upon request, using 8Mhz processor clock

    #include <avr/io.h>
    #include <stdint.h>       // needed for uint8_t

    int ADCsingleREAD(uint8_t adctouse)
    {
        int ADCval;

        ADMUX = adctouse;        // use #1 ADC
        ADMUX |= (1 << REFS0);   // use AVcc as the reference
        ADMUX &= ~(1 << ADLAR);  // clear for 10 bit resolution

        // 128 prescale for 8Mhz
        ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

        ADCSRA |= (1 << ADEN);    // Enable the ADC
        ADCSRA |= (1 << ADSC);    // Start the ADC conversion

        while(ADCSRA & (1 << ADSC)); // waits for the ADC to finish

        ADCval = ADCL;
        ADCval = (ADCH << 8) + ADCval; // ADCH is read so ADC can be updated again

        return ADCval;
    }

    int main(void)
    {
        int ADCvalue;

        while (1)
        {
            ADCvalue = ADCsingleREAD(1);
            // ADCvalue now contains an 10bit ADC read
        }
    }

For more information about analog read, see [this][2].

  [1]: https://techawarey.wordpress.com/2013/12/28/avr-gpio-tutorial/
  [2]: https://sites.google.com/site/qeewiki/books/avr-guide/analog-input


message:
Wifi REST API GET call - how to concatenate and pass URL parameters?

I'm not too familiar with the Arduino C++ language, but I would like to get this native code to work.

In curl this works:

> curl "http://access.alchemyapi.com/calls/text/TextGetTextSentiment?text=i+feel+great&outputMode=json&apikey=my-apikey"^C

So I am trying to use a WiFi client for the same request but it seems the passing and parsing of the URL parameters is causing a problem.

    sprintf(request,"/calls/text/TextGetTextSentiment?apikey=%s&text=%s&outputMode=%s","31adba6dfc3a879b88762f50efc9f892bd573207", "i+feel+great", "json");
    Serial.println(request);

When I print the request, everything after the & gets truncated.

      char serverName[] = "access.alchemyapi.com";
      if(client.connect(serverName,port) == 1)
      {
        sprintf(outBuf,"GET %s HTTP/1.1",page);
        client.println(outBuf);
        sprintf(outBuf,"Host: %s",serverName);
        client.println(outBuf);
        client.println(F("Connection: close\r\n"));
      }

This works (HTTP status 200, though with missing parameters error from the API service) if I only pass in 1 parameter.

body:
Concatenating the string data in memory before sending it shouldn't be necessary. Instead, you should just be able to use `client.print()` (or equivalent) to output each part of the request in sequence. For example:

    client.print("GET ");
    client.print(page);
    client.print(" HTTP/1.1\r\n");

    client.print("Host: ");
    client.print(serverName);
    client.print("\r\n");

    // etc.

That should let you output any combination of HTTP headers you need.


message:
How can I stop someone from hacking in to my Arduino via Bluetooth?

I am using an HC-05 bluetooth Module. How can I stop someone from pairing with my device by brute forcing the key? Failing that, and if someone does pair with my device, is there a way to authenticate the user? I was thinking of salted hash with a shared secret key. Is there anything better?

body:
Configure your Bluetooth module to AT Command Mode

Then use `AT+PIN` Command to change the default PAIRING PIN of the Bluetooth Module.

Visit [this link][1] for more information about how to configure bluetooth to AT Mode

  [1]: http://www.instructables.com/id/AT-command-mode-of-HC-05-Bluetooth-module/?ALLSTEPS


body:
In case someone else asks the same question in the future, here's the answer...

Technically speaking, the Arduino cannot be hacked for the simple reason that it doesn't have an Operating System like other devices such as the Raspberry Pi, BeagleBone, Rock64 etc. So in as much as someone might be able to bruteforce the HC-05 pin and get access, there's pretty much nothing else they can do past that point, so my advice to you is that don't stress over it. However I would suggest adding a few security measures to your HC-05 Bluetooth module:

1. Change the default pin (0000 or 1234) to something else.
2. Lock the module to connect only to a specific device via the MAC Address and the AT+BIND command.

Cheers!


message:
Arduino AD-converter tolerance

I created a quite simple Arduino sketch:

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

    void loop() {
      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);

      float voltage = sensorValue * (5 / 1023.0);
      Serial.println(voltage);

      delay(1000);
    }

I use the following circuit:

![enter image description here][1]

My multimeter measures **3.31 V**, between the pin 3V3 and GND.

I get a *sensorValue* of **730** and a calculated *voltage* of **3.57 V**. This is 8% higher that 3.3V. What is the tolerance by the AD-converter?

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

body:
The absolute accuracy of the ADC in the ATmega328P when its clock is within its optimal range is given [in the datasheet][1] as 2LSB. This means that the actual value could be anywhere between 728 and 732.

Of course this depends on the accuracy of VCC, since it is being used as the ADC reference. This is why supply voltage measurements should be performed using the internal bandgap voltage instead.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


message:
Venus GPS + Arduino. Kill 3.3V TX during sketch upload

I am playing around with the Sparkfun Venus GPS.  I followed [this][1] tutorial to get started.  In here the author states that you should

> Upload the following sketch to your Arduino BEFORE making any
> connections. 5V from an IO pin left high on the Arduino may well kill
> the 3.3V output from the Tx pin on the GPS module.

However, I am using the Sparkfun bi-directional logic level converter in between the Arduino and the Venus GPS (because I'm using the 5V Arduino GSM shield stacked on top of the Arduino).  In that case, would the above statement still apply?

  [1]: http://www.doctormonk.com/2012/05/sparkfun-venus-gps-and-arduino.html "this"

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

If you have a logic-converter between the Arduino and the GPS then you won't have any problems.

The warning was about having the output from the Tx pin on the GPS possibly being damaged by +5 V from the Arduino, if a previously loaded sketch made it an output and HIGH.

However you could just as easily upload a "do nothing" sketch like this:

    int main () { }

That is sound practice anyway, if you are connecting up new hardware and are not sure what the currently-loaded sketch does.


message:
Vibration sensor for arduino

I need vibration sensor for my project. I have found many sensors similar to [this one][1]. But it seems, that this sensor outputs only zeros for "non-hit" state and ones for "hit state". And I need something that can output levels of vibration, not only presence/abscense.

So is there any high-resolution vibration sensor for arduino?

Thank you!

  [1]: https://www.sparkfun.com/products/9196

body:
I assume the OP wants the frequency of the vibration, which an accelerometer such as the ADXL345 won't give.

I have two workarounds: if the expected vibration frequency is low, say, under 100Hz, use instead an on/off vibration sensor (adafruit has them for under a dollar) and count the number of transitions. If it's more, how about a microphone and a band-pass filter?


body:
The MPU-6050 is a very low-price 3 axis gyroscope and accelerometer with both SPI and I2C interface options.

I found mine here:  https://smile.amazon.com/gp/product/B00KKR9ORI

----
EDIT:  Removed statement that it is accurate enough for this, based on comment.


message:
Custom Bootloader on Atmega328p - PU - 28 pin DIP

I am experimenting with low-power wireless arduino modules. For that, I needed 3V powered arduino so that I can do away with voltage regulators which eat up a lot of battery juice.

I am using 28 pin Atmega328p-PU dip IC with 8 MHz external crystal oscillator. Just for trying, I dumped the arduino pro mini 3.3V 8 MHz bootloader into it and it was a success. Everything is working as expected. However, I realized that SMD package which is being used in pro mini has 8 ADC pins compared to 6 in the DIP version.

Should I be worried about it?

Second feasible option is modifying the Arduino UNO board definition to use 8 MHz clock source as compared to 16 MHz and leave everything else same. Do you think this will serve my purpose?

body: The Atmega328p has 8 analog inputs. Some packages (such as the DIP) don't have enough pins to bring all of them out, but they are in there. The SMD package brings all of them out, but it apparently the Pro Mini does not pick up two of them. The net result is the same - 6 useable and 2 unusable analog inputs.


message:
How do I scroll through the LCD vertically with joystick?

I have a device I'm working on and the only issue I'm running into is I can't manage to figure out how to get my LCD display to move around vertically with the joystick I have attached to it. I have a feeling with a tip this could be a very simple fix, but I'm just stuck. So the brief of this is that I need someone to fill in the ???'s for me provided in my example code.

    //Include the LCD Library.
    #include <LiquidCrystal.h>
    #include <Wire.h>
    //Declare the LCD object and define pins.
    #include <MFRC522.h>
    #include <SPI.h>

    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>

    #define SAD 10
    #define RST 5

    //Ignore The below line it is for the master code
    #define I2C_ADDR    0x27 // <<----- Add your address here.  Find it from I2C Scanner
    #define BACKLIGHT_PIN     3
    #define En_pin  2
    #define Rw_pin  1
    #define Rs_pin  0
    #define D4_pin  4
    #define D5_pin  5
    #define D6_pin  6
    #define D7_pin  7

    int n = 1;

    LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

    void setup() {

    //Booting the LCD
      lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
      lcd.setBacklight(HIGH);
      lcd.home (); // go home
      lcd.cursor();

    //Starting settings
      lcd.begin(1,0);
      lcd.clear();

    }

    //Sometimes you have to hit reset on the device

    //Joystick Defaults X=484 Y=513

    void loop() {
      lcd.setCursor(0,0);
      lcd.print("Example");
      delay(100);

    for (int positionCounter = 0; positionCounter = 1; positionCounter++) {
    if(analogRead(1) > 584) {
      lcd.scrollDisplayLeft();
      delay(30);
      } else if(analogRead(1) < 384) {
        lcd.scrollDisplayRight();
        delay(30);
      } else if(analogRead(0) < 413) {
         lcd.???????????????????();
         delay(30);
      } else if(analogRead(0) > 613) {
         lcd.??????????????????();
         delay(30);
        }
      }
    }

body:
The LCD library provides easy functions that activate commands in the LCD itself.  The LCD doesn't have functions that do what you want, so there is no simple vertical scrolling like you're suggesting.

If you need to have it, you'll need to re-write the screen with the content you want to display when the user scrolls around. I can't make any specific suggestions as I don't know the reason you need to scroll around the display this way, but one comprehensive method would be to create a buffer of data the LCD should be displaying, then scroll it using software (move the bytes around the way you want) and then send that buffer to the LCD when it changes.

There may be other more applicable or easier tricks, but that would largely depend on your specific use case and user interface design.


message:
Comparing orientation data obtained using gyroscope and accelerometer

Recently, I have been playing around with a gyroscope and accelerometer in the hopes of building a quadcopter. I have plotted some of the data the two sensors and I am noticing that the pitch from the accelerator lags significantly behind the gyroscopic pitch.

From some research, I understand that these two are not going to equivalent values due to the mechanisms of measurement, however is it common to have such large discrepancies (i.e a difference of 20 degrees or higher) between the two sensors or is this an issue with my conversion?

I have listed the graph and source code [here][1]. Any help would be appreciated!

Sincerely,
Anand

  [1]: https://www.dropbox.com/sh/lemczvtzstgdhcj/AAAYqmxft7sWJ-tMkcKaA2d7a?dl=0

body:
Normally the values from gyroscope will drift overtime. It is natural and depends on the parameters of your code. It could drift a few degrees per seconds and the data will be far way from the accelerometer in a few seconds.

I have seen that you have applied the complementary filter, so you don't need to worry about the single value from the gyros since you combine them with the acceleromter and everything seems fine.

The gyros are good for short time response, in long time response the values get pretty bad as they drift a lot.

On the other hand, accelerometers are good for long time response, since short time response is noisy because of gravitational influence.

That's why you need a filter to combine them.

Wrapping up, it is normal to have this behavior in gyros. If you want to know more about the effect behind this sensor, try this [reading][1].

  [1]: http://en.wikipedia.org/wiki/Coriolis_effect


message:
Reading data from airspeed v3 eagle tree

I am trying to get values from this sensor **Airspeed v3** from eagle tree but it seems my I2C is not working properly.

I bought a module in third party mode and followed these [instructions][1] from the manufacturer website.

I went to rcgroups forum and discovered the right values for the bits mentioned in the documentation about WRITE and READ.

I started the development of a code but I cannot get the values from the sensor. It is supposed to send me a 2 byte-formatted value indicating the airspeed measured. But surprisingly when I call this method `Wire.requestFrom(AIRSPEED_ADDRESS, 2)` it returns 0, so someway the communication is not working. I have used I2C before for ADXL345 sensor and it works perfectly.

The results from these lines

    Serial.println(data[0]);
    Serial.println(data[1]);

  are just -1 indicating that no data is available to display.

Does anybody know how to get this working? Am I missing something?

This is my code right now.

    #include <Wire.h>

    #define AIRSPEED_ADDRESS  0xEA
    #define WRITE_BIT         0x00
    #define READ_BIT          0x01

    void setup() {
      // join I2C bus (I2Cdev library doesn't do this automatically)
      Wire.begin();
      Serial.begin(9600);
      Serial.println("Program started");
    }

    void loop() {
      byte data[2] = {0};
      int i = 0;
      int16_t velocidade = 0;

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      if (!Wire.write(WRITE_BIT)) {
        Serial.println("error sending write_bit");
      }
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      if (!Wire.write(0x07)) {
        Serial.println("error sending 0x07");
      }
      Wire.endTransmission(false);

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      if (!Wire.write(READ_BIT)) {
        Serial.println("error sending read_bit");
      }
      else {
        //Serial.println("ok sending read_bit");
      }
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Serial.print("bytes read from slave: ");
      Serial.println(  Wire.requestFrom(AIRSPEED_ADDRESS, 2) );
      data[0] = Wire.read();
      data[1] = Wire.read();
      Wire.endTransmission();

      velocidade = data[1] | (data[0] << 8);
      Serial.println(data[0]);
      Serial.println(data[1]);
      Serial.println(" ");

    }

  [1]: http://www.eagletreesystems.com/Manuals/microsensor-i2c.pdf

body:
That's interesting but after using a different library the code worked out.

It has to follow exactly what the datasheet says in order to get things done.

The following source code makes it and get the airspeed from the sensor:

    #define SENSOR_ADDRESS 0xEA
    #include <Wire.h>
    #include <I2cMaster.h>
    TwiMaster AIRSPEED_SENSOR(true);

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

    long airspeed_update(void) {
      static struct {
        union { int16_t val; uint8_t raw[2];
        } airspeed16;
      } airspeedv3;

      long airsp;

      if(AIRSPEED_SENSOR.start(SENSOR_ADDRESS | I2C_WRITE)) {
        delay(10);
        AIRSPEED_SENSOR.write(0x07);
        delay(10);
        AIRSPEED_SENSOR.stop();
      }

      if(AIRSPEED_SENSOR.restart(SENSOR_ADDRESS | I2C_READ)) {
        delay(10);
        airspeedv3.airspeed16.raw[0]=AIRSPEED_SENSOR.read(false);
        delay(10);
        airspeedv3.airspeed16.raw[1]=AIRSPEED_SENSOR.read(true);
        delay(10);
        AIRSPEED_SENSOR.stop();
      }

      airsp=airspeedv3.airspeed16.val;
      return airsp;
    }

    void loop() {
      int airspeed = airspeed_update(); Serial.println(airspeed);
      delay(50);
    }

Get this library from [here][1].

  [1]: https://github.com/landis/arduino/tree/master/libraries/I2cMaster


body:
I found the I2C address on my Eagletree Airspeed V3 sensor to be 0x75 NOT 0xEA.

the following code adapted from first sample above works on my Nano:

    /*
     * note that timming is critical - see delay (5)
     * and bps set to 115200
     * works ok, but clean up 5-19-2019 jaf
     */

    #include <Wire.h>

    #define AIRSPEED_ADDRESS  0x75
    #define WRITE_BIT         0x00
    #define READ_BIT          0x01

    void setup() {
      Wire.begin();
      Serial.begin(115200);
      Serial.println("Program started");
    }

    void loop() {
      byte data[2] = {0};
      int i = 0;

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Wire.write(WRITE_BIT);
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Wire.write(0x07);
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Wire.write(READ_BIT);
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Wire.requestFrom(AIRSPEED_ADDRESS, 2);
      data[0] = Wire.read();
      Wire.endTransmission();

      Serial.println(data[0]);
      delay(5);
    }


message:
How to control 2 servos at same time in sync?

For overcoming torque issues, I have attached 2 *identical* servos on a certain part of my robot arm and because I saw someone do the same.

Now, while writing code I realize:

    #include <Servo.h>
    ...
    ...
 shoulder1.write(map(analogRead(p1), 0, 1023, 0, 179));
 shoulder2.write(map(analogRead(p1), 0, 1023, 0, 179));
    ...

will turn `shoulder1` by 20* and then `shoulder2` by another 20*, ie. an overall turn of 40*; that too with too much load on servos, as the other servo would be inactive at the time first is active.

I want to achieve 20* fully-sync.ed turn on both servos, how do I accomplish this? Any arduino libraries or walkthrough?
______
Can I possibly move them [both at the same time][1] - something like [multithreading][2] on arduino? Here's what I tried:

 void rotateTwoServoInSync(int angle) {
  for(int i = 0; i<angle; i++) {
   shoulder1.attach(9);
   shoulder1.write(i);
   shoulder1.detach();
   shoulder2.attach(10);
   shoulder2.write(i);
   shoulder2.detach();
  }
 }

Will it work? Is this approach recommendable?

  [1]: http://playground.arduino.cc/ComponentLib/servo
  [2]: http://forum.arduino.cc/index.php?topic=4854.0

body:
`analogRead()` and `map()` are slow; only perform them once.

    unsigned char rot = map(analogRead(p1), 0, 1023, 0, 179);
    shoulder1.write(rot);
    shoulder2.write(rot);


body: If you have two RC servos that are always required to move together you can simply connect both control inputs to a single output.


body:
Spehro's answer is the most obvious. But note that there is no such thing as identical servos. You may stress them if you connect them through a stiff connection.

If you want to have two mechanical parts make the same movement the proper solution is to connect them mechanically, rather than have two servos doing the same action.


body: To operate two or more servos at the same time you need to interpolate their movements, first moving one servo a little, then moving the next one, back and forth until all servos arrive at their destination point. I haven't seen a library yet that accomplishes this for you so you probably need to write your own routine. Here is a project where I interpolated three servos and includes the code: https://www.instructables.com/id/MonkeyBot-3-Servo-Climbing-Robot/


message:
Do multiple ultrasonic sensors need an external power source?

So maybe it's a very low class form of question, but please bear with me. I'm working on a project with 7 HC-SR04 ultrasonic sensors connected to one Arduino. I tried to unify the trigger and echo pin, but the sensing isn't good enough, so I dropped the Uno and convert it to Mega. My question is, do I need external power source for those 7 Sensors? And how do I connect all of them? Thanks

body:
Well, according to [the datasheet](http://www.micropik.com/PDF/HCSR04.pdf) the "working current" is 15mA.  Even if you had all 7 working at once, which I doubt you will - you'll be working through them in sequence I guess - that would be just 105mA - way below the 800mA the Arduino's on-board regulator can supply, and only a fifth of what a USB port can provide.

The datasheet doesn't mention the quiescent (idle) current, but it will be a tiny fraction of that 15mA and so can mostly be ignored.  Running the sensors in sequence, which is the most likely scenario, would use about the same amount of current as if you had 1 sensor - or 20 sensors.  Most of the current consumption would be while you are actively producing an ultrasonic chirp.

So no, you don't need an external power supply to run them all - just take them all from the Arduino's 5V pin.


body:
You will probably not have any kind of problem with the Arduino power source, while in the test bench. When using it for the Drone/Bot you seem to be working, make sure to have a stable power source to the Arduino, and, if possible, let your sensors have their own energy input.

I had previous experiences with the sensors not working properly because the Arduino was not getting enough energy through the Arduino's pins when mounted.


message:
Sending serial data to Processing

I have a question about using the Arduino and Processing. I want to build a touch sensor using aluminum foil and connect it to an interface built in Processing. However i've come across a problem. I don't know how to send the serial data from the Arduino to Processing. This is the code I'm using to get the sensor value from the aluminum foil:

    #include <CapacitiveSensor.h>

    CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);

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

    void loop(){
      long start = millis();
      long total1 =  cs_4_2.capacitiveSensor(30);

      Serial.print(millis() - start);
      Serial.print("\t");

      Serial.print(total1);
      Serial.print("\t");
      Serial.print('\n');

      delay(100);
    }
The foil is connected to dig pin 4 with a resistor of 1M in between and to dig pin 2 with a resistor of 1K. Pin 4 is the send pin, pin 2 is the receive pin. It all works just fine, in the serial monitor in the Arduino software I get the value of the time between refreshes and the sensor value. But how do I use this sensor value in a Processing sketch? I thought of maybe using Firmata on the Arduino, but then I wouldn't know how to use the CapacitiveSensor library and get the sensor values. Does anyone know how to get this to work? Help would be greatly appreciated!

body: SparkFun has [a tutorial](https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing) where they explain in great detail how to create a project where your Arduino communicates with Processing on your PC.


body: You're already half way there - you're sending the data from the Arduino.  All you need to do now is read up on how to use Serial in Processing (hint: Arduino is based on Processing, so you should already know most of it) in order to read what you're sending.


body:
Try to use this code:

    // Graphing sketch

    import processing.serial.*;

    Serial myPort;        // The serial port
    int xPos = 1;         // horizontal position of the graph

    void setup () {
    // set the window size:
    size(400, 300);

    // List all the available serial ports
    println(Serial.list());
    // I know that the first port in the serial list on my mac
    // is always my  Arduino, so I open Serial.list()[0].
    // Open whatever port is the one you're using.
    myPort = new Serial(this, Serial.list()[0], 9600);
    // don't generate a serialEvent() unless you get a newline character:
    myPort.bufferUntil('\n');
    // set inital background:
    background(0);
    }
    void draw () {
    // everything happens in the serialEvent()
    }

    void serialEvent (Serial myPort) {
    // get the ASCII string:
    String inString = myPort.readStringUntil('\n');

    if (inString != null) {
    // trim off any whitespace:
    inString = trim(inString);
    // convert to an int and map to the screen height:
    float inByte = float(inString);
    inByte = map(inByte, 0, 1023, 0, height);

    // draw the line:
    stroke(127,34,255);
    line(xPos, height, xPos, height - inByte);

    // at the edge of the screen, go back to the beginning:
    if (xPos >= width) {
    xPos = 0;
    background(0);
    }
    else {
    // increment the horizontal position:
    xPos++;
    }
    }
    }

Also look at: http://www.arduino.cc/en/Tutorial/Graph


message:
How to make an RC mixer with the arduino

I want to make a RC mixer mixing two channels of a receiver.

What I have: a delta model plane, two servos, a receiver and a Arduino Nano.

So I'd like to mix the aileron (two channels) with the elevator(one channel).

EDIT: What I've done: I read the input of the receiver and wrote it to the servos. The problem: The servo stutters and the arduino displays false inputs.

    int pin = A0;
    int pin1 = A1;
    unsigned long duration;
    unsigned long dur;

    unsigned long duration2;
    unsigned long dur2;

    #include <Servo.h>

    Servo myservo;
    Servo myservo2;

    void setup()
    {
      Serial.begin(9600);
   myservo.attach(9);
    }

    void loop()
    {
      duration = pulseIn(pin, HIGH);
      dur = duration;
      Serial.println(dur);
      myservo.writeMicroseconds(dur);
      delay(50);
    //  duration2 = pulseIn(pin1, HIGH);
    //  dur2 = duration2-980/4-200;
    //  Serial.println(dur2);
    //  myservo2.write(dur2);
    }

body:
You do not need to use long for values from pulseIn, using int will be sufficient.

Your code is not complete, at least there is a missing '}' at the end of setup.

The slower the baud rate (9600) actually the more it interferes with timing code, to a point.  PWM is all timing code.  I would suggest 57,600.

You never set the servos to any pins.  And is using Servo lib needed? I have always used [analogWrite][1] with no problems.

You are not using parenthesis on your math (currently commented). It will not give you the result you expect. But you are somewhat on the right track, subtract 1500 from each pulse read, that will give you -/+ range. How you mix that depends on how your radio is setup (servo reversing, which channel is which). Keep in mind ailerons is 1 channel, so left aileron = -rightAileron.  Elevator up = that + elevator.  so;

aileronLeft = airleronChannel + elevatorChannel<br>
aileronRight = -airleronChannel + elevatorChannel

You do realize this a [$3 part][2]?

update: I have always used analogWrite, but I also always use good equipment. I see cautions that cheapo servos might be damaged with analogWrite. You can read more [here][3]. It has always worked for me.

  [1]: http://www.arduino.cc/en/Reference/analogWrite
  [2]: http://www.hobbyking.com/hobbyking/store/__6321__TURNIGY_V_Tail_Mixer_Ultra_small.html
  [3]: http://forum.arduino.cc/index.php?topic=5701.0


message:
Arduino-uno sending email with Hotmail

I want to get emails read from a Hotmail account using an Arduino Uno. Is there a way to do it with SSL or is there a way to disable SSL?

    #include <SPI.h>
    #include <Ethernet.h>
    // Use comments to enable or disable this define for debug messages
    #define DEBUG_POP
    // Use comments to enable or disable the deleting of the mail
    #define ENABLE_DELETE_POP

    // The mac address must be an unique number
    // A mac generator is used:
    //   http://www.miniwebtool.com/mac-address-generator/
    byte mac[] = { 0xDE, 0x36, 0x5F, 0x0A, 0x19, 0x83 };
    // change network settings to yours
    IPAddress ip(192, 168, 1, 117);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);

    // Set the server POP3 address, the port, the user and password.
    // The POP3 mail server is something like this:
    //     mail.yourdomain.com, pop.yourdomain.com, pop3.yourdomain.com
    // Using PROGMEM for these causes a fail when trying to connect and log in.
    const char pop_server[] = "pop3.live.com";
    const int  pop_port = 995;
    const char pop_user[] = "xxxxxx@hotmail.com";
    const char pop_pass[] = "xxxxxx";

    // The number of milliseconds timeout for parseInt() and find().
    // The response time for the Server can still be 10 seconds.
    #define POP_TIMEOUT 10
    #define POP_TIMEOUT_DEFAULT 1000

    EthernetClient client;

    void setup()
    {
     Serial.begin(9600);
     Serial.println(F("\nArduino POP3 email reader"));

     pinMode(13, OUTPUT);     // the system led is used for testing

     // When the Ethernet Shield is used, there is also a SD card connected
     // to the SPI bus. Disable the SD card with chip select at pin 4.
     pinMode(4, OUTPUT);
     digitalWrite(4, HIGH);

     // Start Ethernet. Use only the 'mac' parameter for DHCP
     // Use 'mac' and 'ip' parameters for static IP address.
     //  Ethernet.begin( mac, ip);
     //  Ethernet.begin( mac, ip, gateway, gateway, subnet);
     if (Ethernet.begin(mac) == 0)
     {
      Serial.println("Failed to configure Ethernet using DHCP.");
      // no point in carrying on, so do nothing forevermore:
      while (1);
     }
     Ethernet.begin(mac, ip, gateway, gateway, subnet);
     // print your local IP address.
     Serial.println(F("Ethernet started."));
     Serial.print(F("Local IP = "));
     Serial.println(Ethernet.localIP());

     Serial.println(F("Press 'c' to check mail."));
    }

    void loop()
    {
     // Create a buffer to receive the commands in (that is the Subject of the mail).
     char buffer[32];

     byte inChar = Serial.read();
     if (inChar == 'c')
     {
      // The getEmail gets the text of the mail Subject into the buffer.
      // The valid number of received characters are returned.
      // If the return value is < 0, it is an error.
      int n = getEmail(buffer, sizeof(buffer));

      if (n < 0)
      {
       Serial.print(F("Email POP3 failed, error = "));
       Serial.println(n);
      }
      else
      {
       if (n == 0)
       {
        Serial.println(F("Ready, nothing to do."));
       }
       else
       {
        // 'n' is > 0, a command received.
        Serial.print(F("Email checked, Command = \""));
        Serial.print(buffer);
        Serial.println(F("\""));

        // Check the commands.
        //
        // At this moment, a single command 'L' is used to set system led on or off.
        //    L=1   (set led on)
        //    L=0   (set led off)
        if (buffer[0] == 'L' && buffer[1] == '=')
        {
         digitalWrite(13, buffer[2] == '0' ? LOW : HIGH);
        }
       }
      }
     }
    }

    // getEmail
    // --------
    // Find an email on a mail server, using POP3.
    // The Subject should start with "ARDUINO " and the text
    // after that is copied into pBuf.
    //
    // The data in pBuf is only valid if the return value is not an error
    // (an error is return value less than zero).
    //
    int getEmail(char *pBuf, int nBufSize)
    {
     // nBytes is the number of bytes that is returned by getEmail.
     int nBytes = 0;

     // Connect to server
     // client.connect returns '1' if okay, or negative number if error.
     //    SUCCESS 1
     //    0     (error, unknown timeout, perhaps an error in the library)
     //    TIMED_OUT -1
     //    INVALID_SERVER -2
     //    TRUNCATED -3
     //    INVALID_RESPONSE -4
     //    -5    (there is no mail server at that IP address and port)
     // The string for the server must be a normal string in sram, no PROGMEM allowed.
     int nError = client.connect(pop_server, pop_port);

     // During testing, a value of zero was sometimes returned.
     // This is not according to the documentation and it is an error.
     // Therefor the non-error value '0' is turned into a negative number to
     // indicate an error.
     if (nError == 0)
      return(-200);

     // Only a value of 1 is okay.
     if (nError != 1)
      return(nError);

    #ifdef DEBUG_POP
     Serial.println(F("connected"));
     //Serial.println(nError);
    #endif
     // The server should respond with "+OK" and maybe more text after that.
     // Check if "+OK" can be read.
     // The parameter 'true' is to read also everything after the "+OK".
     if (!readOk(true))
      return -102;

    #ifdef DEBUG_POP
     Serial.println(F("command USER"));
    #endif
     client.print(F("USER "));
     client.println(pop_user);
     if (!readOk(true))
      return -103;

    #ifdef DEBUG_POP
     Serial.println(F("command PASS"));
    #endif
     client.print(F("PASS "));
     client.println(pop_pass);
     if (!readOk(true))
      return -104;

    #ifdef DEBUG_POP
     Serial.println(F("command STAT"));
    #endif
     client.println(F("STAT"));
     if (!readOk(false))
      return -105;

     // The whole line was like this: "+OK 3 15343"
     // It means that 3 emails are waiting with a total size of 15343.
     // At this moment, the "+OK" is read, but nothing else.
     // Check if there is a space after "+OK".
     char c = client.read();
     if (c != ' ')
      return -106;

     client.setTimeout(POP_TIMEOUT);       // set timeout lower for parseInt
     // Read the number of emails that are on the server.
     int nMails = client.parseInt();
     client.setTimeout(POP_TIMEOUT_DEFAULT);  // restore timeout to 1 second

     // Read the remaining of the response to STAT.
     readRemaining();

    #ifdef DEBUG_POP
     Serial.print(F("Number of emails="));
     Serial.println(nMails);
    #endif

     // Test if there are emails waiting.
     if (nMails == 0)
     {
      // No emails, but no error. Set buffer to empty string.
      nBytes = 0;               // the returned value
      pBuf[0] = '\0';           // set empty string
     }
     else if (nMails > 0)
     {
      // emails are waiting.
      // Scan the emails until the first is found with the keyword "ARDUINO " at the
      // beginning of the "Subject: ".

      boolean found_and_ready = false;
      for (int nMailNumber = 1; nMailNumber <= nMails && !found_and_ready; nMailNumber++)
      {
       // The command RETR <x> gets the whole mail.
       // The command TOP <x> <size> gets the header plus 'size' of the body.

    #ifdef DEBUG_POP
       Serial.print(F("command TOP "));
       Serial.print(nMailNumber);
       Serial.println(F(" 0"));
    #endif
       client.print(F("TOP "));
       client.print(nMailNumber);
       client.println(F(" 0"));

       // Use readOk with parameter 'false' to stop reading after "+OK".
       if (!readOk(false))
        return -107;
       // The header of the email is waiting to be read, use the Stream.find() to look for the Subject.
       // The text "Subject: " should be at the beginning of a line, but that is not tested.
       // The first found text "Subject: " is assumed to be the real subject.
       // I have checked many years of emails, and the text is always "Subject: ", and never "SUBJECT: ".
       // At the moment, it is not possible to use the F() macro for Stream.find
       // Only the email that starts with "ARDUINO " at the start of the Subject is used.

       client.setTimeout(POP_TIMEOUT);      // set short timeout for find().
       // find() returns true if found and false if not.
       boolean foundsubject = client.find("Subject: ARDUINO ");
       client.setTimeout(POP_TIMEOUT_DEFAULT);   // restore timeout to 1 second

       if (foundsubject)
       {
    #ifdef DEBUG_POP
        Serial.println(F("Found an email for me"));
    #endif

        // Read the remaining subject (that is the command for the Arduino) into a buffer.
        // Every line from the mail server should end with CR + LF,
        // but to be sure, both CR and LF are checked.
        // Alternative:
        //    client.readBytesUntil('\r', pBuf, nBufSize);

        // The last position in the buffer is reserved for the zero terminator.
        // So read data until (nBufSize-1).
        int i;
        for (i = 0; i < (nBufSize - 1) && client.available(); i++)
        {
         char c = client.read();
         if (c == '\r' || c == '\n')
          break;
         pBuf[i] = c;
        }
        // Add zero terminator
        pBuf[i] = '\0';
        nBytes = i;     // the number of received bytes is returned by the getEmail() function.

        // More text of the header could be following the Subject.
        // That is read and disregarded.
        readRemaining();

    #ifdef DEBUG_POP
        Serial.print(F("Subject = \"ARDUINO "));
        Serial.print(pBuf);
        Serial.println(F("\""));
    #endif

    #ifdef ENABLE_DELETE_POP
        // Delete the just read message.
    #ifdef DEBUG_POP
        Serial.print(F("command DELE "));
        Serial.println(nMailNumber);
    #endif
        client.print(F("DELE "));
        client.println(nMailNumber);
        if (!readOk(true))
         return -108;
    #endif

        // Everything is okay, the mail is read and deleted.
        // Ready for now, don't process the remaining emails.
        found_and_ready = true;
       }
       else
       {
    #ifdef DEBUG_POP
        Serial.println(F("No ARDUINO keyword in subject"));
    #endif
        // This email has no "Subject: ARDUINO ".
        // But the remaining text has still to be read and disregarded.
        readRemaining();
       }
      }
     }

    #ifdef DEBUG_POP
     Serial.println(F("Sending QUIT"));
    #endif
     client.println(F("QUIT"));

     // After "QUIT", the server still respons with "+OK",
     // but after that, the connection might get lost.
     // So don't read everything after "+OK" (use parameter 'false' for readOk).
     if (!readOk(false))
      return -109;

     client.stop();

    #ifdef DEBUG_POP
     Serial.println(F("normally disconnected"));
    #endif

     return(nBytes);
    }

    // Read the response from the mail server.
    // That is "+OK" if everything is okay.
    // Parameter 'readAll' is to read every character after the "+OK".
    boolean readOk(boolean readAll)
    {
     // Check the response "+OK" from the mail server
     // In most cases that is followed by a space and more text, but not always.
     // In case of an error the text "-ERR" is received.

     int loopCount = 0;
     char bufOk[4];
     Serial.print("Connected: ");
     Serial.println(client.connected());

     Serial.print("Client Available: ");
     Serial.println(client.available());
     // Wait for response of mail server, with a timout.
     while (!client.available())
     {
      delay(1);
      loopCount++;

      // if nothing received for 10 seconds, timeout
      if (loopCount > 10000)
      {
       client.stop();
    #ifdef DEBUG_POP
       Serial.println(F("\nTimeout"));
    #endif
       return false;
      }
     }

     // Read the first three bytes.
     client.readBytes(bufOk, 3);

    #ifdef DEBUG_POP
     Serial.write(bufOk, 3);
     Serial.println();
    #endif

     // Is it "+OK" ?
     if (strncmp(bufOk, "+OK", 3) != 0)
     {
      popFail();
      return false;
     }

     // When the text after "+OK" is not needed, everything
     // else can be read and disregarded
     // (or shown in the serial monitor during debugging).
     if (readAll)
      readRemaining();

     return true;
    }

    void readRemaining()
    {
     // This function is called after checking the "+OK".
     // It reads everything from the server, until no more text is
     // available.

     while (client.available())
     {
      char c = client.read();
    #ifdef DEBUG_POP_EXTRA
      Serial.print(c);
    #endif
     }
     return;
    }

    void popFail()
    {
     int loopCount = 0;

    #ifdef DEBUG_POP
     Serial.println(F("popFail"));
    #endif

     while (!client.available())
     {
      delay(1);
      loopCount++;

      // if nothing received for 10 seconds, timeout
      if (loopCount > 10000)
      {
       client.stop();
    #ifdef DEBUG_POP
       Serial.println(F("\nTimeout"));
    #endif
       return;
      }
     }

     client.stop();

    #ifdef DEBUG_POP
     Serial.println(F("disconnected due to fail"));
    #endif
    }

Output:

    Arduino POP3 email reader
    Ethernet started.
    Local IP = 192.168.1.117
    Press 'c' to check mail.
    connected
    Connected: 1
    Client Active: 0

    Timeout
    Email POP3 failed, error = -102

body:
Hotmail doesn't provide a non-encrypted POP3 service, which would normally run on port 110.

You have no choice but to use the SSL service.  However, you can't.  Or not easily.  SSL is quite a heavy protocol and it is highly doubtful the little Uno is capable of even coming close to being able to work with it.

The Due might have a chance, but again, unlikely.

You would be best off using a computer (server) to check the emails for you and provide a "digest" of information to the Uno instead.


message:
How to avoid pulling the RX0 pin to reset sketch

My project requires reading 5 serial devices (RFID readers) at the same time. I chose an Arduino Mega 2560 as it comes with 4 serial RX ports. For the fifth port I am using the SoftwareSerial library.

My loop() checks each Serial port to detect if an RFID tag is being read. This works perfectly.

However, I am powering the board from an wall wart. When the power is disconnected the sketch no longer runs. I must unplug RX0, plug in the power supply, and reattach RX0.

If the board ever loses power it will have to be reset manually which is not ideal.

Please help me understand Why is this happening? and how can I fix it?

body:
It looks like your RFID readers are very chatty on startup, and the board is going into bootloader mode.

I'd consider either controlling the RFID reader's power using another pin (and a transistor or mosfet if the reader needs more than 20mA), or using a gate ( `AND` for instance, or a simple switch IC like the 4066) that you can control to disable the `RX0` input until program start.

Another thing I've done in the past is multiplexed multiple serial devices to one serial input.  The RFID readers probably have outputs that indicate a card presence, so use those and a multiplexor.  When the card presence is indicated, connect that serial port using the multiplexor, read the card and act accordingly, then wait for another card detect event.


body:
You can simply disable the bootloader rather than erasing it. Find out the current fuse settings using a fuse-detection program. Change the BOOTRST flag in the High fuse to be unchecked, referring to this page: [Engbedded Atmel AVR® Fuse Calculator](http://www.engbedded.com/fusecalc)

Write the High fuse back. Then it will ignore the bootloader and go straight to your code. Of course, to upload a new version you will have to put the BOOTRST fuse back, or you won't be able to use the bootloader to upload a new sketch.

One way of changing the fuse is to use my [Atmega chip stand-alone programmer sketch](http://www.gammon.com.au/uploader). This has an interactive "change fuses" option. To run this you just need a spare board (eg. a Uno) and 6 wires to connect the programming board to your target Mega2560.

Example wiring shown on the linked page. Note that you do **not** need the SD board to merely change fuses. Just the two Arduinos and the connecting wires are enough for that.

When you first run the sketch it should inform you of the current fuses. Look at the High fuse and follow my instructions above.

You should see something like this:

    Entered programming mode OK.
    Signature = 1E 98 01
    Processor = ATmega2560
    Flash memory size = 262144
    LFuse = FF
    HFuse = D8
    EFuse = FD
    Lock byte = FF
    Bootloader in use: Yes

In this case the High fuse was D8, which has the bootloader enabled. Using the Fuse Calculator site we can see that it should now be D9 which disables the bootloader.

---

An alternative way to change the fuse is to use Avrdude, if you have a stand-alone ISP programmer handy.


message:
What protocols and tools does Arduino Due use for flashing and debugging?

I am interested in writing a simple C program *outside* of the Arduino IDE and respective libraries, but deploying it directly to an Arduino Due (which uses a SAM3X8E ARM MCU). I am trying to figure out what comms/serial protocols are used for:

* Flashing/deploying the program to the ARM MCU; and
* Connecting the program to a debugger

And, not just the protocols used, but what *tools* are compatible with these protocols, and henceforth, can be used for both use cases. How can I tell what my viable options are?

body:
The Due (more specifically the SAM3X) uses its own proprietary protocol. It's all embedded in the bootloader, which is hard wired in the ROM and can never be changed (idiotic if you ask me).

I know of two systems for communicating with it.  Atmel's SAM-BA program, and the open source [BOSSA](http://www.shumatech.com/web/products/bossa).  The command line version of BOSSA (bossac) is used by the Arduino IDE for programming.


message:
This specific code just refuses to compile?

I've been working on some software to do REALLY basic composition of music.
Here's my code so far:

    #include "notes_sharps.h"

    int notes[] = {NOTE_B0,NOTE_C1,NOTE_D1,NOTE_E1,NOTE_F1,NOTE_G1,NOTE_A1,NOTE_B1,NOTE_C2,NOTE_D2,NOTE_E2,NOTE_F2,NOTE_G2,NOTE_A2,NOTE_B2,NOTE_C3,NOTE_D3,NOTE_E3,NOTE_F3,NOTE_G3,NOTE_A3,NOTE_B3,NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5,NOTE_D5,NOTE_E5,NOTE_F5,NOTE_G5,NOTE_A5,NOTE_B5,NOTE_C6,NOTE_D6,NOTE_E6,NOTE_F6,NOTE_G6,NOTE_A6,NOTE_B6,NOTE_C7,NOTE_D7,NOTE_E7,NOTE_F7,NOTE_G7,NOTE_A7,NOTE_B7,NOTE_C8,NOTE_D8};

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

      for(int i = 0; i < 51; i++){
        Serial.println("%i's sharp is %i",notes[i], notes[i]+(notes[i]*0.05937));
      }
    }

    void loop(){}

This code just refuses to compile, no error messages, it simply leaves my computer dormant.
Here's the log:

`C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10604 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp -o C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp.o
`

body:
As Majenko stated in the comments, your use of the println function is not valid as there exists no overload that takes char*, int, int as parameters.

You could get your program to work by replacing your println as following:

    for(int i = 0; i < 51; i++){
        Serial.print(notes[i]);
        Serial.print("'s sharp is ");
        Serial.println(notes[i]+(notes[i]*0.05937));
    }


message:
Problem using Ino build for 8 MHz

I want to use the [Ino command line toolkit](http://inotool.org/) to build and upload my HEXes. It works well for the regular Arduino, however when I try to upload code to a Mini Pro 3.3V at 8 MHz, the code has the timing wrong. The serial output is garbled (I tried at different baud rates and was garbled each time) and `delay(1000);` seems to take double the time. I have selected the correct board (pro328 in my boards.txt), but it didn't seem to make a difference in the generated code. Has anyone used this and encountered a similar problem?

body:
Per the [Quick start guide][1], Ino assumes the board is an Arduino Uno unless otherwise specified on the command line:

> All examples were done in assumption that you have Arduino Uno and it is available on default port. Now consider you have Arduino Mega 2560 and it is available on port `/dev/ttyACM1`. We have to specify this for our build steps as command-line switches.
>
> Board model may be set with `--board-model` or `-m` switch. Port is set with `--serial-port` or `-p` switch. So lets do it:
>
>     $ ino build -m mega2560
>     $ ino upload -m mega2560 -p /dev/ttyACM1
>     $ ino serial -p /dev/ttyACM1
>
> For the full list of board names refer to `ino build --help`.

So you might be able to do this by using

    $ ino build -m pro328
    $ ino upload -m pro328 ...

However I don't know what options Ino includes for boards (presumably it uses the boards file), so using `ino build --help` should give you the information you need to select a suitable board if `pro328` doesn't work.

Once that's done, the frequency setting should be taken care of for you.

  [1]: http://inotool.org/quickstart


body:
So it seems the F_CPU should be set up at compile time and I'm not sure if Ino does that or not (probably, or I'm missing something else).

However after pulling my hair for a day or so I discovered [PlatformIO](http://platformio.org/#!/) which has a much better functionality - my code works correctly, the lib manager is intriguing, is platform independent and seems it doesn't even require the Arduino environment to be installed (it can pull the required files itself).


message:
ATMega1284 and Relative Humidity libraries

I am trying to use some Relative Humidity sensors (DHT11 and DHT22) with the ATMega1284 processor on a breadboard. I use libraries from Arduino playground (dht.h), Adafruit (DHT.h) and others. Even though both sensors and libraries work fine with Arduino Uno and Mega, they fail with ATMega1284, which produces an INVALID_VALUE error.

Connections are double checked, and other libraries such as Wire, OneWire etc work fine.

Does anyone have any experience with the ATMega1284 processor, or any suggestions?

body:
Per the library instructions, you will receive `INVALID_VALUE` in the following situations:

> The `readXX()` functions return:
>
> * `DHTLIB_OK` (0) : if the sensor sample and its checksum is OK.
> * `DHTLIB_ERROR_CHECKSUM` (-1) : if the checksum test failed. This means that data was received but may be incorrect.
> * `DHTLIB_ERROR_TIMEOUT` (-2) : if a timeout occured, communication failed.
>
> In case of a `DHTLIB_ERROR_TIMEOUT`, humidity and temperature will both get the value `DHTLIB_INVALID_VALUE`. In case of `DHTLIB_ERROR_CHECKSUM` the values of humidity and temperature are left unchanged as it is impossible to determine which byte failed in the checksum. It is up to the programmer to decide what to do. One can compare with previous value, but better reread the sensor.

So read the value returned by the `read11()` or `read22()` functions to verify that it's an `DHTLIB_ERROR_TIMEOUT` condition, and if so try to figure out why the library is having trouble talking to the device.


message:
Need help rewriting a program

I can't use this program on my Arduino Uno since the max is 16 bits. I need my water pump to run for 5 min, then wait for 60 min.

    int motorPin = A0;
    int blinkPin = 13;

    int watertime = 300000; // how long to water in miliseconds
    int waittime = 3600000; // how long to wait between watering

    void setup() {
        pinMode(motorPin, OUTPUT);
        pinMode(blinkPin, OUTPUT);
    }

    void loop() {
        digitalWrite(motorPin, HIGH);
        digitalWrite(blinkPin, HIGH);
        delay(watertime);
        digitalWrite(motorPin, LOW);
        digitalWrite(blinkPin, LOW);
        delay(waittime);
    }

---
Changed int to:

    #define watertime 300000
    #define waittime 3600000

But it does not work.

body:
Use the `long` type instead

    long watertime = 300000; // how long to water in miliseconds
    long waittime = 3600000; // how long to wait between watering


body:
If did not misunderstand, you want a longer delay. Why don't you use a for loop in order to obtain such a delay.

    for(int i = 0; i < 50; i++) {
        delay(1000);
    }

This produces 50 seconds instead of 1 second. You can replace 1000 and 50 according to your needs. This is just an example.


body:
For any delays longer than a few seconds you really need to use a Real-Time Clock chip, like the popular DS1307 from Maxim. The Arduino's delay() function is only very roughly accurate, and even less so when used as you are using it.

If you can't get a DS1307 or something similar (there's plenty to choose from) or you Arduino has too much connected already to allow anything else to be added, you could use the `Time` library to simulate one.  The `Time` library is also useful if you do have an RTC attached.

* http://playground.arduino.cc/code/time


body:
I do not know if you plan on doing anything else on your arduino, but holding a delay inside the loop function is bad idea if you do, things need to happen outside of your code (any serial I/O for sure and others, right?).

That said, I like @zgrknr answer the best, although the others will also work. That answer allows using smaller numbers, that are easier to understand. Just make sure to keep your variables global, and not within loop or else they will get re-initialized every time.

As far as accuracy, do some real by the clock testing, and adjust your numbers, who cares if it is accurately counting as long as you can identify what numbers gives you the time period you want.

response to comment:

My firmware code looks like this, is yours different?

    int main(void)
    {
   init();
   initVariant();

    #if defined(USBCON)
   USBDevice.attach();
    #endif

   setup();

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


body:
I believe it's better to put the Arduino to sleep instead of using the delay function.

You can use a library called [*Sleep_n0m1*](https://github.com/n0m1/Sleep_n0m1) for the purpose.

Modify your code like following.

    #include <Sleep_n0m1.h>

    int motorPin = A0;
    int blinkPin = 13;

    unsigned long watertime = 300000UL; // how long to water in miliseconds
    unsigned long waittime = 3600000UL; // how long to wait between watering
    Sleep sleep;

    void setup()
    {
        pinMode(motorPin, OUTPUT);
        pinMode(blinkPin, OUTPUT);
    }

    void loop()
    {
        digitalWrite(motorPin, HIGH);
        digitalWrite(blinkPin, HIGH);
        sleep.pwrDownMode();
        sleep.sleepDelay(watertime);
        digitalWrite(motorPin, LOW);
        digitalWrite(blinkPin, LOW);
        sleep.pwrDownMode();
        sleep.sleepDelay(waittime);
    }

Hope this would solve the problem.


message:
How to program thresholds?

Hello guys (and gals)!

I'm trying to figure out how to program thresholds using my arduino board.

Essentially, to make this as simple as possible, this is what I have going on.

I am sampling a value every one second, I am taking the value and trying to make certain actions occur based on when this value crosses certain thresholds.

The value read every second will be a value between 0-150.

The thresholds will work something like this:

If value crosses over 20 and becomes 20 or higher, do an action.

If value crosses over 20 and becomes 19.9 or less, do a different action.

And then do the same for a threshold at 30, 40, 50, and 65.

I would need to have it so that if it reads a value of 15, and then a second later, reads a value of 23, it does an action. But if it reads 23, and then reads 24 a next, it needs to not do anything because it hasn't crossed over from one threshold to another. I only want an action to perform if a threshold is crossed either by increasing or decreasing past it.

So again, to reiterate;

If first value read is 34, and second is 42, do an action.

If first value is read at 57, and second at 44, do an action.

If first value is 24, and second value is 26, do nothing. (no threshold was crossed)

The next part would be figured out if a threshold was crossed twice, or more, to do that action twice or more times.

Any advice on how to code this?

Thanks in advance.

body:
The way you described it, the first and good solution I can approach it is [state machine.][1]

You have a lot of thresholds to check and very specific details such as going up at some level and doing something or nothing depending on the level.

What I advise you is creating the state machine for you code setting up all the thresholds and saving the actual *state* of your system into a variable. After you have this set up, coding is just a matter of switch/cases or if statements.

For example. The first part is to check if it goes until 20 and then keep with at least 20.

    switch (state) {
        case 1:
            if (value >= 20 && value < 30)
                 state = 2;
            break;
         case 2:
            if (value < 20)
                 state = 1;  // initial state
            else if (value >= 20 && value < 30)
                 state = 3; // or call a function
            break;
         case 3:
              doSomething();
              break;
    }

And you could have some delay or timer interrupt to check the value each 1s and repeat the state machine again and again. If you change or read the value inside an interrupt function call, make sure you declare the variable as **volatile** otherwise the compiler will optimize it and your machine won't work properly.

This way you can expand the idea and have all the thresholds set up.

  [1]: http://en.m.wikipedia.org/wiki/Finite-state_machine


body:
Thanks again for your contributions.

I've gone ahead and decided to go with the following code. Its purpose is to turn vol up or down based on current car MPH. I choose to define brackets that cover a range of values. When one bracket ends, another begins. I've also set the previous bracket to current bracket at the end of each loop so that the application knows where it was previously, so that if it hops above or goes under a defined bracket, it does the desired action.

I've used a random generator to supply the MPH for testing purposes for now and commented out a few things that disturbed the testing process. If you'd like to critique this code to make is better, please let me know.

Note: I've also borrowed some of this code from another individual (Matthew McMillan, http://matthewcmcmillan.blogspot.com) who wanted to figure out how to convert a vehicle speed sensor wire info into MPH. I needed this code in order to make use of the vehicle's speed.

    #include <SPI.h>
    #include <Wire.h>

    const int lightPin = 0;
    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;
    unsigned int imph;
    int roundedMph;
    int previousMph;
    int prevCount;

    // Declare brackets
    const int BracketA = 1;
    const int BracketB = 2;
    const int BracketC = 3;
    const int BracketD = 4;
    const int BracketE = 5;
    const int BracketF = 6;

    // Initialize Previous and Current Brackets
    int PreviousBracket = 1;
    int CurrentBracket = 1;

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

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

    void loop() {

      /////////////////////////////////////////////////////////////
      // 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.
      imph = (unsigned int) mph; // Cast to integer. 10x allows retaining 10th of mph resolution.

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

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

      //Code to write your own MPH for testing purposes.
      //if (Serial.available() > 0) {
                    // read the incoming byte:
                   // roundedMph = Serial.read();
                   //}

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

      roundedMph = random(1,80);

      // Don't display mph readings that are more than 50 mph higher than the
      // previous reading because it is probably a spurious reading.
      // Accelerating 50mph in one second is rocketship fast so it is probably
      // not real.
      if((roundedMph - previousMph) > 50){
        roundedMph = previousMph;
      }

      //Place the gatherered MPH value into a bracket
      //---------------------------------------------
      if(roundedMph >= 0 && roundedMph < 20) {
       CurrentBracket = BracketA;  //Value1
       Serial.println("I Choose Bracket A");
        }

      if(roundedMph >= 20 && roundedMph < 30) {
       CurrentBracket = BracketB;  //Value2
       Serial.println("I Choose Bracket B");
        }

      if(roundedMph >= 30 && roundedMph < 40) {
       CurrentBracket = BracketC;  //Value3
       Serial.println("I Choose Bracket C");
        }

      if(roundedMph >= 40 && roundedMph < 50) {
       CurrentBracket = BracketD;  //Value4
       Serial.println("I Choose Bracket D");
        }

      if(roundedMph >= 50 && roundedMph < 65) {
       CurrentBracket = BracketE;  //Value5
       Serial.println("I Choose Bracket E");
        }

      if(roundedMph >= 65) {
       CurrentBracket = BracketF;  //Value6
       Serial.println("I Choose Bracket F");
        }

     //Decide if bracket stayed the same, went up, or down.
     //---------------------------------------------------
     if(CurrentBracket == PreviousBracket) {
     //Do Nothing
     Serial.println("Nothing Changed");
     }

    if(CurrentBracket > PreviousBracket) {
     //Command for Vol Up
     int VolUp;
     VolUp = CurrentBracket - PreviousBracket;
    Serial.println("Volume Went Up One by ");
    Serial.println(VolUp);
    delay(2000); // Delay to not change Vol to fast if near threshold
    }

    if(CurrentBracket < PreviousBracket) {
      //Command for Vol Down
      int VolDown;
      VolDown = PreviousBracket - CurrentBracket;
     Serial.println("Volume Went Down One by ");
     Serial.println(VolDown);
     delay(2000); // Delay to not change Vol to fast if near threshold
     }
      previousMph = roundedMph; // Set previousMph for use in next loop.
      PreviousBracket = CurrentBracket; //Set PreviousBracket for use in next loop.
    }


message:
How can I programming detect that a Bulb/LED is ON/OFF or a circuit is working as expected using Arduino?

I've created a circuit to turn on bulb using GSM module and Arduino. I want a mechanism(or programming) to know whether the bulb is on or off or fused. I've tried taking the input from the pins. But it only tells whether the pin is on or off but not the circuit as a whole.

body:
This can be done using a few methods.  The simplest and least expensive option is to measure the current consumption of the device you want to verify correct operation of, and see if it's using enough, but not too much, current.

For instance, the following would work well in the arduino case of using an LED:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/7ySWi.png)

<!-- End schematic -->

Connect the `Power` to 5V or to the pin you're controlling the LED with. Connect the `Sense` to an analog input such as A0.

If the LED isn't installed, or is broken as an open circuit, the sense would register 5V.  If the LED is broken as a shorted element, the sense would register 0v. If the LED is operating correctly, you would sense the voltage drop of the LED (which varies according to the LED's design), but it would be well above 0V and well below 5V.

For bulbs and other loads, use a much smaller resister for R1 (so the resistor doesn't affect the load as much) and it would be considered a current shunt.  Knowing the resister value, and the voltage at the `Sense` location will give you a current value using `Current = Voltage / Resistance`. Again, the load should be drawing current within an acceptable range during proper operation.  If it's not drawing enough current, or too much current, it may not be operating correctly.

This won't tell you if the LED is on, however it's a very reliable method to discover if it's working correctly, and you'll probably never run into a situation where the correct LED is installed and in the right current range, but not emitting light.


message:
Disturbed digital out at 4Mhz on Arduino NANO

I've written a simple program - it generates signals over `Port D` at 4 MHz:

    #include <Arduino.h>

    int main(void) {

     DDRD = B11111111;
     PORTD = B00000000;

     while (true) {
      PORTD = 0;
      PORTD = 5;
      PORTD = 10;
      PORTD = 15;
      PORTD = 20;
      PORTD = 25;
      PORTD = 30;
      PORTD = 35;
      PORTD = 40;
     }
     return 0;
    }

and this is the signal coming out on D4:
![Max Frequency][2]

I've modified the program by inserting NOP after each assignment to `POTRD`:

    #define NOP __asm__ __volatile__ ("nop\n\t")

    int main(void) {

     DDRD = B11111111;
     PORTD = B00000000;

     while (true) {
      PORTD = 0;NOP;
      PORTD = 5;NOP;
      PORTD = 10;NOP;
      PORTD = 15;NOP;
      PORTD = 20;NOP;
      PORTD = 25;NOP;
      PORTD = 30;NOP;
      PORTD = 35;NOP;
      PORTD = 40;NOP;
     }
     return 0;
    }

and now signal looks fine, but frequency is limited to 800 KHz:
![enter image description here][3]

What is the reason for interference at 4 MHz? Is there a limitation to maximal frequency on digital out? I do not really need it for some particular project, just wanted to know it.

  [1]: https://stackoverflow.com/questions/30201318/disturbed-digital-out-at-4mhz-on-arduino-nano
  [2]: https://i.stack.imgur.com/O3IfR.jpg
  [3]: https://i.stack.imgur.com/gKU53.jpg

I've asked this question on [stackoverflow][1], but then I've discovered this dedicated forum so... I've decided to try it out ;)

body:
This is not a limitation of the Arduino: you can toggle a pin on every clock cycle. It's a synchronization problem between the generated signal and the triggering of the scope. Your scope displays several traces superimposed, and it synchronizes them on the rising edges, but since those are unequally spaced, it gets out of sync with the full period of the signal. By adding a few nops you reached a lucky synchronization in your second version of the code.

The simplest solution is to set the scope mode to _Single_ instead of _Normal_. Then it only displays a single trace and synchronization is not an issue anymore.

Another option would be to use one of the bits of `PORTD` as a trigger
signal. This bit should cycle only once inside the loop. `PD5` should
work in the current version of your code. Configure the scope for
external trigger and feed this signal into its TRIG input.


body:
Thank you - correct trigger solves my problem:
![enter image description here][1]

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


message:
Can I change the USB device name of Arduino?

I have several Arduinos connected to my Windows PC, and they appear as follows:

> COM7 (Arduino Uno)
> COM11 (Arduino Uno)
> COM13 (Arduino Uno)

So there's no way to tell which is which, and when I want to upload a sketch to one, I have to unplug the others to make sure my code goes to the right one.

Is there a way to change the "Arduino Uno" description?

(I found a similar question but that was about Mac specifically).

body:
You'll have to change the software on the Arduino USB chip itself, and you may need to modify the drivers for the Arduino USB interface on the computer side.  It's not trivial, and probably not worth it.

However, Windows attempts to use the same serial port for the same devices in the same USB positions, so if you figure out which is which (blinking the LED at different frequencies) then you can mark the USB port itself with the com number that Windows uses when you plug an arduino into it.

If you use a hub, and you move that hub to a different port, the com numbers will change, but if you keep it in the same port, then it too will try to have them match what they have been in the past.

It's an annoyance, but it's a design decision by arduino.cc.  The old FTDI chips kept their assigned com port numbers because they have individual serial numbers and windows would attempt to reassign the same com port to the same chip each time it was plugged in, regardless of its location.  When Arduino.cc moved to a programmed MCU for the USB interface, they chose not to provide USB serial numbers, and thus windows has little option but to try to keep things straight by determining the location in the USB hierarchy that the device is connected, and try to keep com port assignments the same using that method.


body:
I have never tried it, but I suspect using zadig might work;
[http://zadig.akeo.ie/][1]

It lets you pick the driver and name for WinUSB and LibUSB devices.  Uninstall any existing driver first. And remember to pick the driver you wish to use when it asks. Also it is not real apparent, but you can edit the name of the device as it installs the driver.

Let us know if it works

  [1]: http://zadig.akeo.ie/


message:
Difference between Arduino.cc and Arduino.org

Recently I have noticed that there are two arduino sites, arduino.cc and arduino.org.  They both have the Arduino logo and both sell what seems to be official Arduino boards. Also, arduino.org came out with the Arduino Zero board first. What is the deal here? Has Arduino partnered with another site? Any ideas appreciated.

body:
This article can explain it better than I could paraphrase:
http://hackaday.com/2015/02/25/arduino-v-arduino/

Relevant excerpt:

> Arduino LLC [***arduino.cc***] is the company founded by Massimo Banzi, David Cuartielles, David Mellis, Tom Igoe and Gianluca Martino in 2009 and is the owner of the Arduino trademark and gave us the designs, software, and community support that’s gotten the Arduino where it is. The boards were manufactured by a spinoff company, Smart Projects Srl, founded by the same Gianluca Martino. So far, so good.
>
> Things got ugly in November when Martino ... renamed Smart Projects to Arduino Srl and registered ***arduino.org***
>
> According to this [Italian Wired article][1], the cause of the split is that Banzi and the other three wanted to internationalize the brand and license production to other firms freely, while Martino ... [wanted] to list on the stock market and keep all production strictly in the Italian factory.

  [1]: http://www.wired.it/gadget/computer/2015/02/12/arduino-nel-caos-situazione/


body:
The short of it is that there was a falling out within the Arduino people and now there are two groups laying claim to the "Arduino" name.

Arduino LLC runs arduino.cc. They are the steward of the Arduino IDE and libraries and own the "Arduino" trademark in the United States, and also owns the "Genuino" trademark outside of the United States. Arduino SRL (fka Smart Projects SRL) is the company that assembles(assembled) the majority of Arduino boards for Arduino LLC, runs arduino.org, and owns the "Arduino" trademark inside Italy and all of the other countries they have registered the "Arduino" trademark.

Arduino SRL recently decided that they are no longer beholden to Arduino LLC and has stopped paying licensing fees for using the Arduino name. Whether this is justified or not has not been fully tested in court yet.


body:
[arduino.org][1] is not only boards assembler, but is also who designs and engineers the arduino boards. They own the arduino trademark all over the world, except the USA, therefore [arduino.cc][2] owns the trademark only in the USA.

  [1]: http://www.arduino.org
  [2]: http://www.arduino.cc


body: Please take a look at [The Untold History of Arduino](http://arduinohistory.github.io).


body:
Update on the situation: on October 1st, 2016 a blog post at arduino.cc "[Two Arduinos become one][1]" announced that an agreement was found between arduino.cc and arduino.org. Two key points:

 - the creation of a foundation
 - the creation of a holding.

About the holding:

> At the end of 2016, the newly created “Arduino Holding” will become the single point of contact for the wholesale distribution of all current and future products, and will continue to bring tremendous innovations to the market.

About the foundation:

> In addition, Arduino will form a not-for-profit “Arduino Foundation” responsible for maintaining the open-source Arduino desktop IDE, and continuing to foster the open-source movement by providing support for a variety of scholarships, community and developer initiatives.

  [1]: https://blog.arduino.cc/2016/10/01/two-arduinos-become-one-2/


message:
Arduino SoftwareServo by example

I am interested in writing a simple Arduino program that will turn a servo back and forth (180 degrees each time) continuously.

I am looking at [these servos](http://www.amazon.com/VicTsing-10pcs-Helicopter-Airplane-controls/dp/B00KA393PK/ref=sr_1_1?s=wireless&ie=UTF8&qid=1431615089&sr=1-1&keywords=VicTsing+10pcs+micro+servo+motor+SG90) and am planning on following [this example](http://playground.arduino.cc/ComponentLib/servo).

Being so new to Arduino, I first wanted to confirm that the `SoftwareServo` library in that example will drive those particular servos. If it will not, then can someone begin by explaining to me *why* these servos are incompatible with the lib?

Assuming they are compatible, I am looking at the main example on that page (comments stripped out for brevity):

    #include <SoftwareServo.h>

    SoftwareServo myservo;

    int potpin = 0;
    int val;

    void setup() {
        myservo.attach(2);
    }

    void loop() {
        val = analogRead(potpin);
        val = map(val, 0, 1023, 0, 179);
        myservo.write(val);
        delay(15);

        SoftwareServo::refresh();
    }

My concerns:

* There seem to be 3 pins involved here: a potentiometer pin (`0`), an analog pin (`val`) and a servo pin (`2`). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?
* Is there anything "wrong" with defining `myservo.attach(2);` up *above* the `setup` function, and leave the `setup` function an empty no-op function?
* Where does the `map(...)` function come from? If it was defined inside `SoftwareServo` I would have expected its usage to be something like `SoftwareServo::map(...)`, etc.
* Why do we need the `delay` after calling `myservo.write(val);`? What would happen if this delay wasn't in there?
* According to that link, calling `SoftwareServo::refresh()` once every 50ms is necessary in order to: "*keep your servos updating.*" **But what does this mean, really?** Updating to what?!?

body:
> There seem to be 3 pins involved here: a potentiometer pin (0), an analog pin (val) and a servo pin (2). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?

No, there is only 2 pins.  The value of the potentiometer attached to pin 0 is read and stored in the variable `val`.  That is then used to set the angle of the servo motor on pin 2.

> Is there anything "wrong" with defining myservo.attach(2); up above the setup function, and leave the setup function an empty no-op function?

Yes.  It'll never get called.  `setup()` is the first function to be called and its purpose is to perform any initialization routines, such as attaching the servo code to the pin the servo is connected to.  So you *have* to call that either from `setup()` or from a function which `setup()` itself calls.

> Where does the map(...) function come from? If it was defined inside SoftwareServo I would have expected its usage to be something like SoftwareServo::map(...), etc.

`map()` is part of the standard Arduino API.  http://www.arduino.cc/en/Reference/Map

> Why do we need the delay after calling myservo.write(val);? What would happen if this delay wasn't in there?

You don't need the `delay()` call, but you don't want to set the value of the servo too rapidly.  You really want to allow at least one PWM cycle between each call to ensure the values have been set properly.

> According to that link, calling SoftwareServo::refresh() once every 50ms is necessary in order to: "keep your servos updating." But what does this mean, really? Updating to what?!?

SoftwareServo is just what it says - a piece of software.  You have to run that software for it to work, and the `refresh()` function is that bit that you run.  If you don't call that then the PWM signal for the servo will never get generated and nothing will happen.

Oh, and yes those little servos should be fine.


body:
1- there is only two pins a servo pin which is D2 and an analog pin which is A0. D2 pin for writing analog value to servo. D2 pin is used for getting analog pin value.

2- map function is a default function like sin, cos or digitalRead so library inport not necesary.

3- delay function and waiting 50ms is used to wait servo response time. if you change servo angle too quickly servo will not respond accurately


message:
Measure SRAM usage

I am using an Arduino with 2048 bytes of SRAM. I have a complex project so that it is no longer obvious how much SRAM it would use in total (there is not one large dominant object but many different routines, many libraries most of which I have not written myself etc. Each of these uses some small buffers, global variables etc.).

Can I determine how much SRAM I have left in the live system?

body:
Expanding on my previous comment... The RAM memory map of an AVR-based
Arduino looks like this:

    ┌──────┬─────┬──────┬──────────┬───────┐
    │ data │ bss │ heap │→  free  ←│ stack │
    └──────┴─────┴──────┴──────────┴───────┘

The data and bss sections are fixed, and their size can be known at
compile time. However, the stack and the heap grow and shrink
dynamically as the program runs. You can estimate the amount of free
memory at run time by measuring the gap between the heap and the stack.
The result may be pessimistic if the heap contains usable holes.

Here you have:

* [a very simple function](https://learn.adafruit.com/memories-of-an-arduino/measuring-free-memory) that does exactly that, and
* [a more complex version](http://playground.arduino.cc/Code/AvailableMemory) that also counts the holes in the heap.


message:
Is EEPROM persisted across program flashes?

If I use `EEPROM.write(someAddr, someValue)` to write a value to an address, how long will that value "stick" to that address before being lost?

If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?

body: Only if the `EESAVE` fuse is programmed (it is unprogrammed by default). If not then the EEPROM will be erased when a chip erase command is performed.


body:
> how long will that value "stick" to that address before being lost?

The Atmega328 data retention is guaranteed by Atmel (the manufacturer) for 20 years at 85 degrees Celsius, 100 years at 25 degrees Celsius. Beware cheap Chinese clones usually use counterfeits chips, meaning those values are not going to be guaranteed any more

> If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?

While @ignacio answer is more detailed I believe you are interested in plain Arduino IDE programming along with standard Arduino boards, in which case the answer is **yes**, the data is not going to be erased.


message:
Arduino won't send serial data if connected with external power supply

I am trying to make a connection between 2 Arduino's with the APC220 rf modules.

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

    void loop() {
       int value = 5;
       Serial.println(value);
       delay(1000);
    }

I uploaded this code to my Arduino Nano and Uno. I disconnected the rf modules for uploading the code.

I tried to run this program with an external power source (lipo 11.1V 2200mAh).
The Arduino is powered on(power led is on) BUT the tx led doesn't blink.

The only way to make it work is by using the usb and opening the serial monitor on my pc.

I tried to use a 10k resistor between tx and rx (or rx to ground) but the code won't run...

Can someone help me?

Solution : the arduino worked perfect. When you connect the arduino with an exernal power supply the tx and rx lights won't light up, Even when they are transmitting or receiving.

body: I think tx not activated without available serial connection. What is you rf module and what is the baud rate of RF module. Also can you share connection diagram or a test video. Alternativeliy you can look SoftwareSerial: http://www.arduino.cc/en/Reference/SoftwareSerial


body:
Solution : The Arduino worked perfectly. When you connect the Arduino with an external power supply the Tx and Rx lights won't light up, Even when they are transmitting or receiving.

---

I'm adding this as the solution to stop this being re-added as an unsolved problem.

---

That is correct. The Tx and Rx LEDs are connected to the Atmega16U2 processor, and thus only flash if there is serial comms via USB.