body:
I am a new Arduino user. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Basically, I want to automatically shut down the computer after saving all open documents before my UPS battery goes out whenever I am not there to manually shut it down. I am trying to notify the computer about the power failures of main supply - AC 220V 50 Hz (notification/signal sent when power goes out) via USB using Arduino. I am thinking that this can be done by using the external voltage power supply pin. Whenever power goes out in the mains, the external voltage power supply pin will drop to 0 V from 7 V. The value of the voltage can be read using software ( I am unclear about this: Can it be done? If yes, how?). The Arduino will still be powered up as it is connected to USB of computer and thereby communicates to the computer about the power failure.

title: What happens if I power the Arduino with both the USB and external power voltage simultaneously?

Answers: 2

body:
From arduinoBoardUno:

># Power
>
>The Arduino Uno can be powered via the USB connection or with an external power supply. The power source is selected automatically.

Put the external power through a voltage divider or transistor-based inverter and into an analog (divider) or digital (inverter) pin and check the appropriate value from the pin. Note that this does not require powering the Uno from external power, only connecting the grounds.

body:
>I am a novice user of Arduino. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Lets study the schematic of [Arduino UNO R3](http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf)

The input from the power supply plug (PWRIN, the power jack) goes through a diode D1 (to prevent reverse polarity), and feeds a [NCP1117](http://www.onsemi.com/pub/Collateral/NCP1117-D.PDF) regulator that down converts it to the 5v supply that feeds the 5v parts.

![Power input][1]

The alternative supply comes from the USB plug (USBVCC). The relevant circuit is shown below

![enter image description here][2]

The USB power lines goes through a P-mosfet (T1) that operates as a switch and then goes to the +5V node (that is the +5v regulator output as shown in the first schematic).

The mosfet is controlled by an [LMV358](http://www.onsemi.com/pub/Collateral/LMV321-LMV358-LMV324-D.PDF) operational amplifier (OPAMP) that operates as a comparator.
The negative input of the opamp is tied to 3.3V and the positive one fed through a voltage divider with half the Vin supply level.

 - When Vin >6.6V then the + input of the opamp become higher than the - input and the opamp turns the mosfet off.

 - When Vin <6.6V then the + input of the opamp become lower than the - input and the opamp turns the mosfet on.

Note that Vin is after the input diode so it's about 0.6V lower than the external connected power supply level. So when there is power supply connected to the power input that is higher than 6.6V+0.6V (where 0.6V is the diode D1 voltage drop), then the USB supply line is cutoff (because the mosfet turns off) and the power is provided from the power plug. Connecting or disconnecting the USB supply in this case will not make a difference, so you can have both power supplies connected simultaneously, only when the power input drops below the specified level (about 6.6V+0.6V=7.2V), the USB will start powering the board.

  [1]: https://i.stack.imgur.com/bNsoC.jpg
  [2]: https://i.stack.imgur.com/r9NgC.gif


body:
Does the Arduino Yun does it have a RTC?

And if so is it connected to the Atheros AR9331 or the ATmega32u4?

If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

title: Arduino Yun does it have a RTC?

Answers: 2

body:
> the Yún doesn’t have a real time clock IC on board, so it can’t keep time when is powered off. Instead, it synchronizes with time servers automatically when it powers up and connects to a network using NTP.

*([Arduino Blog](http://blog.arduino.cc/2013/09/02/arduino-yun-hardware-review/))*

Therefore, the **Yun does *not* have a onboard RTC.**

> If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

Probably not. It comes in a [LPCC package](https://www.google.com/search?q=LPCC+package&espv=210&es_sm=122&source=lnms&tbm=isch&sa=X&ei=n6kwU5ncHaSHygGduoGYDQ&ved=0CAoQ_AUoAg&biw=1280&bih=899), which has the solder joints on the bottom. This needs to be soldered by reflow. The Yun does not have any pins connected directly to that chip. You're probably thinking of the ATmega32u4, the actual Arduino chip. The other one is for a router.

**To get the time, you have two options:**

 - **[Use the time from the time server](http://arduino.cc/en/Tutorial/TimeCheck)**

    A few notes:
    > The Yún must be connected to a network to get the correct time. If you used the web-based WiFi interface to configure the Yún for the network, make sure you've selected the proper time zone.
 - **Connect it to a DS1307** (I find [this Adafruit tutorial helpful](http://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit)) You'll need only two pins to use this board. One note: there is a way to connect up to 121 I2C devices using these two pins. However, that gets a little more complicated.

body:
What happens with your Arduino YUN is that it has an internal clock which sincronizes with a computer (at least this is what I do).
However I have read that it can be automatically but I could not do that; have you got a probable solution?


body:
Can I compile c/c++ code on the linux part of the Arduino Yun?

How complete is the linux part of the Arduino Yun?
Can I scp some c/c++ code onto the Atheros AR9331 chip compile it?

Or must I first crosscompile all software and then put them onto the Atheros?

Answers: 1

body:
The Yun's OS (Linino) is based on OpenWRT, and the official toolchain from OpenWRT does not appear to have changed much. It could probably be done, the question is if you'd really want to though.

The limited resources (storage, RAM, CPU) means you would most likely not fit all the parts of the toolchain for C/C++ compilation (perhaps with the exception of very basic programs without many dependencies). The YUN's package manager (opkg) should contain pre-built packackes if they exist, but given that even the list of packages is only kept in RAM to conserve space, I doubt the entire toolchain with libraries needed to compile useful stuff would fit.

The official way to build things for OpenWRT appears to be cross-compilation on a much beefier machine, if only because it takes a fraction of the time needed by a native compiler. All in all, you're also very likely to save time and resources by cross-compiling and have more resources left on the YUN itself.


body:
I have made a simple program using the `int main() {}` function. It has a delay in it. It is evident the code before the delay is running, but the delay never seems to time out and let the next instructions through. Is this by design?

If I rename the method and call it exactly once from the `loop() {}` function though, it does work.

**Edit:**

The code borrowed the 'main()' function and I suppose redefined it:

    int main() {
        Forward();
        delay(3000);
        Reverse();
    }

    void Forward() {
        //...
    }

    void Reverse() {
        //...
    }

I can see this redefinition of `main()` could cause some serious issues based on the answer below.

title: Should a delay be expected to cause deadlock?

Answers: 1

body:
You don't seem to use standard Arduino stuff since you defined your own `main()` which is normally avoided when programming Arduino.

If you take a look at Arduino provided `main()` (in **hardware/cores/arduino/main.cpp**), you'll see how it is defined:

    #include <Arduino.h>

    int main(void)
    {
     init();

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

     setup();

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

     return 0;
    }

Did you notice the `init()` function call at the beginning?

Its code is defined in **hardware/cores/arduino/wiring.c**; what it does is setup all timers used by Arduino functions, in particular a timer that is needed by `delay()`.

In the same **wiring.c** file, you can also find the definition of `delay()`:

    void delay(unsigned long ms)
    {
     uint16_t start = (uint16_t)micros();

     while (ms > 0) {
      if (((uint16_t)micros() - start) >= 1000) {
       ms--;
       start += 1000;
      }
     }
    }

This will turn into an infinite loop if `micros()` always return the same value, and it does so if `init()` has never been called before.

This is what happens with your code.


body:
On Mac OSX Mavericks, why does Arduino Uno uses serial port named `/dev/cu.usbmodemfa131` while Arduino Nano uses `/dev/cu.usbserial-A702NY8S`?

Are they using different FTDI drivers?

title: Serial port /dev/cu.usbmodemfa131 vs /dev/cu.usbserial-A702NY8S

Answers: 3

body:
Drivers are different. On older boards, such as Duemilanove you may need to actually [download serial drivers][1] to [talk to them][2] at all in Lion, Mountain Lion, Mavericks.
There's some discussion of that problem [here][3].

  [1]: http://www.ftdichip.com/Drivers/VCP.htm
  [2]: https://pixhawk.ethz.ch/tutorials/serial_terminal
  [3]: http://forum.arduino.cc/index.php?topic=114652.0

body: The Uno is not using FTDI drivers **at all**, since it does USB through an ATmega16u2, not an FTDI chip.

body: It's really down to the manufacturer and what they identify their USB side as. I have found that Arduino(tm) provide a more meaningful (to me) identifier, eg `/dev/cu.usbmodemfa131` Whilst the boards that use the FTDI chip have the more serialised numbers `/dev/cu.usbserial-A702NY8S`.


body:
I'm using the `Serial1` of the Arduino Leonardo to send and receive data with another MCU. The following code will always retrieve garbled data:

    byte streamReadResponse;
    Serial1.begin(115200);
    Serial1.setTimeout(9000);
    Serial1.print(cmd);
    Serial1.print('\r');
    Serial1.flush();  //wait for all the data to be sent to the serial
    streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);

But, if I add a `delay(50)` before the Serial1 read, I would get the expected output. The value 50 was found by trial and error.

What am I missing? Why is the `flush()` command not working as expected?

title: Serial.read has garbled data after a Serial.write

Answers: 2

body:
Usually, this kind of issue is the result of the several times by time unity of loop statements execution, with the baudrate defined for your serial i/o it's very possible that the flush are override by the new information input and the result are the "garbage" on that.

On my sketches, ever I put "idle function calls"  in some points of the code to avoid this and works succesfully.

body:
I've finally found that when the MCU  to which Arduino is talking to was initialized, it would send spurious data to the Serial - I guess it would start first with a lower baud rate, and then switch to the programmed baud rate of 115200.

To fix this, I had to ```flush``` the Arduino serial RX before sending any data. So:

    byte streamReadResponse;
    Serial1.begin(115200);
    Serial1.setTimeout(9000);
    while (Serial1.read() >= 0)
               ; // do nothing
    Serial1.print(cmd);
    Serial1.print('\r');
    Serial1.flush();  //wait for all the data to be sent to the serial
    streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);


body:
I'm trying to build an Arduino example without using its IDE. My OS is **Windows 8.1** and I'm using the last version of **CMake (2.8.12.2)** and **MinGW (GNU Make 3.82.90)**.

I downloaded [the Arduino CMakeLists](https://github.com/queezythegreat/arduino-cmake) and I learned all about ``make/upload`` any firmware in my Arduino. I'm using **Arduino UNO**.

Then, if I modify the CMakeLists saved in ``~/arduino-cmake-master/example/CMakeLists.txt`` (***arduino-cmake-master*** is the repository folder) to build the WiFi example ***WiFiWebClient*** too:

    ...

    #Add the WiFi example -> WiFiWebClient
    generate_arduino_example(wifi_example
                         LIBRARY WiFi
                         EXAMPLE WiFiWebClient)
    ...

And execute:

      $ cmake -G "MinGW Makefiles"

      ...

      CMake Warning (dev) in example/CMakeLists.txt:
      Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
      interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
      cmake_policy command to set the policy and suppress this warning.

      Target "uno_example" has an INTERFACE_LINK_LIBRARIES property.  This should
      be preferred as the source of the link interface for this library but
      because CMP0022 is not set CMake is ignoring the property and using the
      link implementation as the link interface instead.

      INTERFACE_LINK_LIBRARIES:

        uno_CORE;uno_example;uno_Wire

      Link implementation:

        uno_CORE;uno_Wire

    This warning is for project developers.  Use -Wno-dev to suppress it.

    CMake Warning (dev) in example/CMakeLists.txt:
      Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
      interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
      cmake_policy command to set the policy and suppress this warning.

      Target "uno_Wire" has an INTERFACE_LINK_LIBRARIES property.  This should be
      preferred as the source of the link interface for this library but because
      CMP0022 is not set CMake is ignoring the property and using the link
      implementation as the link interface instead.

      INTERFACE_LINK_LIBRARIES:

        uno_CORE;uno_Wire

      Link implementation:

        uno_CORE

    This warning is for project developers.  Use -Wno-dev to suppress it.

    CMake Warning (dev) in example/CMakeLists.txt:
      Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
      interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
      cmake_policy command to set the policy and suppress this warning.

      Target "uno_SPI" has an INTERFACE_LINK_LIBRARIES property.  This should be
      preferred as the source of the link interface for this library but because
      CMP0022 is not set CMake is ignoring the property and using the link
      implementation as the link interface instead.

      INTERFACE_LINK_LIBRARIES:

        uno_CORE;uno_SPI

      Link implementation:

        uno_CORE

    This warning is for project developers.  Use -Wno-dev to suppress it.

    CMake Warning (dev) in example/CMakeLists.txt:
      Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
      interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
      cmake_policy command to set the policy and suppress this warning.

      Target "uno_WiFi" has an INTERFACE_LINK_LIBRARIES property.  This should be
      preferred as the source of the link interface for this library but because
      CMP0022 is not set CMake is ignoring the property and using the link
      implementation as the link interface instead.

      INTERFACE_LINK_LIBRARIES:

        uno_CORE;uno_WiFi

      Link implementation:

        uno_CORE

    This warning is for project developers.  Use -Wno-dev to suppress it.

    -- Generating done
    -- Build files have been written to: ~/arduino-cmake-master

Later I execute:

    $ mingw32-make

    ...

    Linking CXX static library libuno_WiFi.a
    [ 89%] Built target uno_WiFi
    Scanning dependencies of target wifi_example
    [ 92%] Building CXX object example/CMakeFiles/wifi_example.dir/wifi_example_WiFiWebClient.cpp.obj
    Linking CXX executable wifi_example.elf
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::status()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:160: undefined reference to `ServerDrv::getClientState(unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::stop()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:131: undefined reference to `ServerDrv::stopClient(unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::peek()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:117: undefined reference to `ServerDrv::getData(unsigned char, unsigned char*, unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::read()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:101: undefined reference to `ServerDrv::getData(unsigned char, unsigned char*, unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::read(unsigned char*, unsigned int)':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:107: undefined reference to `ServerDrv::getDataBuf(unsigned char, unsigned char*, unsigned int*)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::available()':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:90: undefined reference to `ServerDrv::availData(unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::write(unsigned char const*, unsigned int)':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:73: undefined reference to `ServerDrv::sendData(unsigned char, unsigned char const*, unsigned int)'
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:78: undefined reference to `ServerDrv::checkDataSent(unsigned char)'
    libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::connect(IPAddress, unsigned int)':
    C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:36: undefined reference to `ServerDrv::startClient(unsigned long, unsigned int, unsigned char, unsigned char)'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::hostByName(char const*, IPAddress&)':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:228: undefined reference to `WiFiDrv::getHostByName(char const*, IPAddress&)'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::status()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:223: undefined reference to `WiFiDrv::getConnectionStatus()'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::RSSI()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:181: undefined reference to `WiFiDrv::getCurrentRSSI()'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::SSID()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:169: undefined reference to `WiFiDrv::getCurrentSSID()'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::localIP()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:149: undefined reference to `WiFiDrv::getIpAddress(IPAddress&)'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::begin(char*, char const*)':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:87: undefined reference to `WiFiDrv::wifiSetPassphrase(char*, unsigned char, char const*, unsigned char)'
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:92: undefined reference to `WiFiDrv::getConnectionStatus()'
    libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::init()':
    C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:22: undefined reference to `WiFiDrv::wifiDriverInit()'
    example\CMakeFiles\wifi_example.dir\build.make:95: recipe for target 'example/wifi_example.elf' failed
    mingw32-make[2]: *** [example/wifi_example.elf] Error 1
    CMakeFiles\Makefile2:748: recipe for target 'example/CMakeFiles/wifi_example.dir/all' failed
    mingw32-make[1]: *** [example/CMakeFiles/wifi_example.dir/all] Error 2
    Makefile:74: recipe for target 'all' failed
    mingw32-make: *** [all] Error 2

The problem is the Arduino.cmake because it's not linking correctly with the library WiFi, but it links with the Wire library.

Anyone knows why that warning appears and why Wire links ok but WiFi doesn't?

Thanks!

**Note**: I'm using original code which is in the repository example, I've not modified this one.

title: Warning Arduino CMakeLists "Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES"

Answers: 1

body:
Your question actually has 2 distinct parts:

 1. Why does arduino-cmake generate the warning "Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES..."?
 2. Why does `make`, using the generated MakeFile, fail when building WiFi example?

**First off**, the arduino-cmake "**Policy CMP0022**" is just a warning, not an error. As per [this cmake article][1], that CMP policy has been only recently introduced in **CMake 2.8.12**.

You get this warning simply because arduino-cmake has been created based on an older version of cmake and thus does not specifically support this new policy.

In order to get rid of this warning, the documentation mentions you should add the `cmake_policy(SET CMP0022 OLD)` command to your cmake configuration.

Unfortunately I tried it in the example `CMakeLists.txt` to no avail; maybe it has to be set directly in arduino-cmake files (which I have not tested).

Thus, if you want to get rid of this boring warning, it seems the only solution you are left with is to disable all warnings when launching cmake:

> cmake -G "MinGW Makefiles" -Wno-dev

This works fine and has removed all warnings..

**Your second problem** (the real one I would say) is due to to the structure of WiFi library:
![enter image description here][2]

Indeed, as you can see above, it has a `utility` subdirectory that contains additional source code that **cannot be found by arduino-cmake**, as by default it searches for source code files only at first level directory.

How to solve it? Just tell arduino-cmake to do a **recursive search for the WiFi library**; in your `CMakeLists.txt`, ensure you add the following line:

    set(WiFi_RECURSE True)
    generate_arduino_example(wifi_example
                         LIBRARY WiFi
                         EXAMPLE WiFiWebClient)

The added `set(WiFi_RECURSE True)` line just tells arduino-cmake that, for WiFi library, it should recurse through subdirectories when looking for source code.

I have checked it with "Unix Makefiles" (not "MinGW Makefiles" but I guess that won't make any difference) and it worked fine.

  [1]: https://github.com/Kitware/CMake/blob/master/Help/policy/CMP0022.rst
  [2]: https://i.stack.imgur.com/JUqed.png


body:
I recently noticed how the map() function in Arduino was bulky in both terms of flash space used and time taken to execute, largely because it deals with `long` and involves a division and multiplication.

Many times you can replace maps with more basic functions i.e.

    output = map(input,0,1023,0,255);

can become

    output = input >> 2;

or

    output = map(input,0,1023,1023,0);

can become

    output = 1023 - input;

I have one line in some code that says:

    backlight = map(LDRreading,0,1023,50,250);

How could this be simplified so that it is both space and time efficient?

I'll allow slight differences in output values if it results in a much better solution.

title: What's the most efficient implementation of map(x,0,1023,50,250)?

Answers: 4

body:
You could approximate it quite closely using only two integer operations:

    backlight = (LDRreading / 5) + 46;

That effectively maps input range 0 - 1023 onto output range 46 - 250, so it's fairly accurate. If `LDRreading` is a 2 byte integer type then it should be significantly more efficient (comparatively speaking) than anything which uses `long`.

body:
![Scaling calculation][1]

The screenshot shows a base-2 (i.e. binary) result of calculating the constant part of a mapping. You can approximate this multiplication by a constant by a number of shifts added together. You need to break down each multiplication in the result first:

x * 0.0012 = x >> 3

x * 0.00012 = x >> 4

x * 0.00000012 = x >> 7

Then add these together. You are essentially breaking it down into convenient base-2 multiplies (which can always be represented by shifts) and adds - nearly always more efficient.

This doesn't get you right to 250, but pretty close:

    >>> for i in range(0, 1024, 34):
    ...   print (i >> 3) + (i >> 4) + (i >> 7) + 50
    ...
    50
    56
    62
       [snip]
    235
    241
    247
    >>> print (1023 >> 3) + (1023 >> 4) + (1023 >> 7) + 50
    247

Do all your processing with a left-justified `int` (`ADLAR`=1) though, to minimize errors. The ADC returns a 10bit result, and ADLAR choses if this is aligned to the left or right of the two result registers.

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

body:
How about this, mapping to 50..249?

    output = ((input * 25) >> 7)+50;

Your input range was 1024 (0..1023). Output range is 200 (In the original specification, it would have been 201, which does not divide as neatly). These have a gcd of 8, so `output = (input * (200/8)) / (1024/8) + 50` will do, and the division by a power of 2 can be expressed with a shift. The nice thing is that `1024*25` still fits into a 16 bit integer, so no longs are needed.

If you want full range, you can try throwing in rounding

    output = ((input*25+64) >> 7)+50;

body:
If the input range is limited in size and you have the memory for it nothing beats a simple lookup-table.

like
unsigned char map[1024] = { 50, 50, << more entries here  >>, 250 } ;

You can pre-compute the content in a part of the program that isn't time-critical or just compute the entire table-content beforehand and put it verbatim in the source-code.

Doing a map is just a read of map[] with the original value as index.

If you input range starts with a non-zero number just decrement all inputs by the lower-bound value so you have a 0-base index for the map array. (That works for negative lower-bounds too !)

At most 1 substract (to adjust for a non-zero lower-bound) and 1 addition to calculate the array-base + index.
And a good compiler will be able to optimize it further.

You can't get more efficient than that, but you do need the space to store the table somewhere.


body:
I'm trying to simply access my HC_05 bluetooth module and conduct some AT commands through the Serial Monitor. For some reason though, **it only seems to be returning Null characters,** though it does some to be actually responding to the command in some way (given by the length of Null characters it returns.

![enter image description here][1]

So you can clearly see that the command `AT` and `AT+NAMEdevice` return different data, but they are both all `NUL` blocks. I am viewing the monitor in text. Changing the view to Hex or ASCII does not change results.

Code for this simple program is below:

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup()
    {
      pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(38400);  // HC-05 default speed in AT command more
    }

    void loop()
    {

      // Keep reading from HC-05 and send to Arduino Serial Monitor
      if (BTSerial.available())
        Serial.write(BTSerial.read());

      // Keep reading from Arduino Serial Monitor and send to HC-05
      if (Serial.available())
        BTSerial.write(Serial.read());
    }

Wire Diagram is as [here][2]
*NOTE* I have used both a direct connection to the `5V` and also used a Voltage Divider. Neither changes the `NUL` return.

  [1]: https://i.stack.imgur.com/NnELQ.png
  [2]: http://www.instructables.com/file/FM8W4A2HKZAVRT9

title: Arduino Serial Monitor only returning Null Characters

Answers: 2

body:
This sounds like baud-rate mismatch. These dongles don't have a reset ability; they remember their most recent settings. [See my answer][1] to another user having trouble communicating with one these.

  [1]: https://electronics.stackexchange.com/a/103868/3361

body:
First, change all `Serial.write` to `Serial.print` I think that might be half your problem.

Next,

      pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);

The way you are doing this will probably put the HC-05 into 9600 baud mode. You can fix this one of two ways:

Change ` BTSerial.begin(38400);  ` to ` BTSerial.begin(9600); `

Or, as jfpoilpret suggested, tie the Key pin directly to VCC.  The reason is that in order to go into 38400 baud mode, there must be voltage on Key at the time the module is powered up.  By the time the digital write in your code happens, it's too late.

If for some reason you'd like to have digital control over the Key pin rather than directly wiring it to VCC, yet you'd like the module to operate at 38400 baud, you can simply change the default baud rate by issuing the appropriate AT command - I believe it's `AT+UART=` off the top of my head.

Also, I'm not sure, but jfpoilpret might be right as well about how your serial read/write handling is done within loop() but here is code that I know works:

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX
    char myChar;

    void setup()
    {
      ...
    }

    void loop() {
      while (BTSerial.available()) {
        myChar = BTSerial.read();
        Serial.print(myChar);
      }

      while (Serial.available()) {
        myChar = Serial.read();
        Serial.print(myChar); //echo
        BTSerial.print(myChar);
      }
    }


body:
What is the maximum power consumption (in mW) of the [Arduino Nano 3.0][1], when it is running in its default state (at 16MHz, no LEDs removed) and powered by an external regulated 5V supply so it bypasses the built in voltage regulator?

This will give us an upper bound on the power consumption of the Arduino Nano that can be used during estimates.

![enter image description here][2]

  [1]: http://arduino.cc/en/Main/arduinoBoardNano
  [2]: https://i.stack.imgur.com/ugt9m.png

title: What is the maximum power consumption of the Arduino Nano 3.0?

Answers: 4

body:
Well, it depends on what you have attached to the Arduino. If you are using the pins to do things you will definitely require more current.

If you **ONLY want to power the Arduino**, then I calculated what I think it should be below. (You should also check with someone who owns this device for an experimental value, and not just a calculated value. )

Based on the datasheet (fig 30-8, p 319), I would say the the processor will draw around 2.4 mA at 5 volts.
http://www.atmel.com/images/doc2545.pdf

The USB chip draws around 15 mA depending on several things (p 18)
http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf

Then you have 2 LEDs with 680 ohm resistors. (Assuming 2 volt drop for each led)
(5-2)/680  = around 4 mA per led.

So depending on how much you use the serial port, and the LEDs I would guess around (2.4 + 15 + 4*4) = 33.4 mA

33.4 mA * 5V  = 0.167 Watts

I suspect you want to know to the **total amount of power the Arduino can source**, which is a bit harder to calculate.

The pins can provide up to 200 mA. (p 303 http://www.atmel.com/images/doc2545.pdf)
So 33.4 + 200 = 233.4

I would also add a 20% safety margin (around 50 mA)
So I would want a 280 mA supply, if I was going to attach the Arduino to different things.

**280 mA * 5 = 1.4 Watts**

Let me know if my numbers are way off.

P.S.: Be careful making your own supply. It is critical that the voltage be very stable. An unstable supply can/will destroy an Ardiuno. I suggest using a [linear regulator][1], like the [LM7805][2]. or maybe the [LM317][3]

  [1]: http://en.wikipedia.org/wiki/Linear_regulator
  [2]: http://www.fairchildsemi.com/ds/LM/LM7805.pdf
  [3]: http://www.fairchildsemi.com/ds/LM/LM317.pdf

body:
From website https://store.arduino.cc/usa/arduino-nano:  Each of the 14 digital pins on the Nano can be used as an input or output. They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA.
Therefore i would assume maximum power consumption is 14 x 40mA x 5V = 2.8W, depends on the board effeciency %, for example let's say 80%, so input could be 3.5W, but again you rarely use all 14 pins at once as outputs hence it is way way lower than 3.5W.This is just a ballpoint figure.

body:
"Each of the 14 digital pins on the Nano can be used as an input or output."

There are 6 analog input pins which are also digital pins, you must take those into account.

However, Note 3 under Table 32-2 of the '328P datasheet says:
"Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:

3.1. The sum of all IOH, for ports C0 - C5, D0- D4, ADC7, RESET should not exceed 100mA.

3.2. The sum of all IOH, for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 100mA.

(but ADC6 and ADC7 are analog input only, and should not be sourcing current)

So I would suggest that to keep your Nano healthy, 200mA x 5V = 1W be considered for the IO, and then the amounts noted above for the Power LED, L LED (which is driven by D13), and internal running of the chip be taken into account.

body: Yes, the i/o can source 40mA @ 5v (or 3v3) per pin, but the limit is'nt 40mA from each pin simultainiously but the limit is the processors dissipation. Read the 328A data sheet carefully and the truth will become clear.


body:
Whilst it is possible, and sometimes desirable, to use pin change interrupts to read the state of buttons, it is simpler to poll the state of buttons in `loop()`. This is a commonly used technique.

If you `loop()` executes quickly enough, then button presses are always going to be caught and the user will not be able to perceive any delay or lag.

It is possible that your loop would take so long as to cause a delay or lag to be perceived.

The question is, how long would it be, in general, before a user would see this?

title: How frequently do you need to poll UI buttons before they are perceived as laggy?

Answers: 2

body:
The short answer is that you have **100 miliseconds** to respond to the user if you want them to feel the action occurred instantaneously.

According to [Jacob Nielsen](http://www.nngroup.com/articles/author/jakob-nielsen/) in his book [Usability Engineering](http://www.nngroup.com/books/usability-engineering/), from 1993, which is considered an important reference in Systems Usability and User Experience:

> * **0.1 second** is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.

He also mentions that this basic advice regarding response times has been about the same for many decades [Miller 1968; Card et al. 1991].

I've taken this citation from this article: [Response Times: The 3 Important Limits](http://www.nngroup.com/articles/response-times-3-important-limits/), also writen by Jacob Nielsen.

Note that in this time you must include all time taken to read the button press and give feedback to the user.

Other response time thresholds that are important for user experience, from the same source, but that were not mentioned directly by the OP are:

> * 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
>
> * 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

body:
It's commonly known that people are unable to perceive changes when they happen underneath 10ms after their action. This responsiveness will result in an experience that has recently mostly been described as "snappy". It's noticeable but for users it's hard to put a name on it.

So if you want perfection, take about 15ms of delay. If you want really good, take 100 ms of delay. 100ms is 50ms on average, and will certainly pass for people.

The application and the expected response time is vital too. A sliding door or elevator is given very large tolerance (as the physical object will always take a lot more time) whereas ticket vending machine interfaces are not given any time at all.

The upper limit for polling would be around 1500ms. Around there people will always notice it is slow.

This data is purely personal experience as a gamer and programmer. YMMV and remember that just trying it yourself is the best way to find out how it feels. The only "scientific" answer is the <10 milliseconds, beyond that it's about the ability to perceive the delay (which varies per person and moment) and the tolerance of the user.

As a side note, you can try fluctuating the delays in order to conserve battery or CPU time when the interface is not being used. The user-action, the faster the polling. When the application is doing it's thing, poll very slowly. Better to poll when it matters!


body:
I have done quite a few projects with Arduino, but have never done more than a "Hello World" in C. I am writing my first library, and a lot of the object oriented stuff is going over my head. Anyway, my library is working as it is supposed to, I pass a float to my function and it formats it properly and sends it out over serial. However, I implemented it in a clunky way. The [Arduino API Style Guide](http://arduino.cc/en/Reference/APIStyleGuide) mentions a way that seems much better:

> When using serial communication, allow the user to specify any Stream object, rather than hard-coding "Serial". This will make your library compatible all serial ports on Mega and the Due, and can also use alternate interfaces like SoftwareSerial. The Stream object can be passed to your library's constructor or to a begin() function (as a reference, not a pointer). See Firmata 2.3 or XBee 0.4 for examples of each approach.

Can anybody elaborate on how to do this, or show me some code?

title: Writing First Library - Serial Stream Object

Answers: 1

body:
Here is a simple example (built and tested with a mega2560), with a class that can be passed a Stream object, and sends a Hello over this generic stream object. When constructing the object, you can pass the Stream object you want to actually communicate:

    #include "Arduino.h"

    class MyProtocol
    {
    public:
     MyProtocol(Stream& s):serial(s){}
     void send(){
      serial.println("Hello");
     }
    private:
     Stream& serial;
    };

    MyProtocol p(Serial);

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

    void loop() {
        delay(1000);
     p.send();
    }

NOTE: The serial.println() is not the Serial global object, note the lower case, it is the internal Stream class variable.

If you are confused with the OO and classes, take into account (while you gain more knowledge about it) that this approach can be also used with a simple function, you can pass the serial parameter. Furthermore, it is not necessary to hardwire the Serial interface for ever, you can in fact switch in run time and use a different channel depending on some condition:

    #include "Arduino.h"

    void send(Stream& serial){
     serial.println("Hello");
    }

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

    void loop() {
        delay(1000);
        if(someCondition)
            send(Serial);
        else
            send(Serial1);
    }


body:
I hope this question is specific enough. Basically I want to know if it matters a great deal what kind of Motor Driver IC(s) or pre-assembled kits you use to drive a Unipolar Stepper Motor.

For example: Can the following Driver be used to control this Stepper Motor?

Driver: https://www.sparkfun.com/products/9670

Motor: http://www.jaycar.com.au/productView.asp?ID=YM2754

Thanks!

title: Which type of Motor Drivers to drive Unipolar Stepper Motors?

Answers: 1

body:
It does matter.  There are pros and cons to each different driver setup.

If you wire the motor as a bipolar, which I'm not sure that you can, you can use the driver that you linked, but it is not very good for driving stepper motors.  [https://www.sparkfun.com/products/11876][1] is a better driver for steppers for half the price.  (still have to wire it bipolar)

If you need to stick with unipolar wiring, [PCBheaven.com][2] shows an example using a CD4017, MOSFETs, and diodes to run a unipolar motor.  It will only turn one direction.  Instead you could use a micro-controller, such as an Arduino, in place of the CD4017 along with logic-level MOSFETs to go both directions.

A tutorial on the Arduino site uses a ULN2003A, which is not powerful enough to drive your motor to its full potential (does it need to turn, or turn well?) and doesn't have the diodes (important to protect your IC!), but the Arduino sketches would still work using the schematic from PCBheaven.

A couple of complete driver boards:

[UNIPOLAR STEPPER MOTOR DRIVER][3]

[FANCY UNIPOLAR STEPPER MOTOR DRIVER][4]

  [1]: https://www.sparkfun.com/products/11876
  [2]: http://www.pcbheaven.com/circuitpages/Simple_Unipolar_Stepper_Motor_Full_Step_Controller/
  [3]: http://www.electronickits.com/kit/complete/motor/ck1405.htm
  [4]: http://www.stepperboard.com/SS1010.htm


body: I am finishing up a project- an LED game alarm clock. Seeing as this is a clock, I need to have a way to conserve power, which right now my Uno R3+ is eating up like a politician. My question is, how do I turn the screen off, or turn the back-light off using software only on a Hitachi HD44780 16x2 LCD screen? Or how do I set a sleep mode on one component? The way I plan on turning it off is with an ultrasonic range finder, if I get close it turns on the screen. If anything I say doesn't make sense, ask me to clarify, I'm in a bit of a rush.

title: Changing the brightness on a Hitachi HD44780 LCD screen

Answers: 2

body:
Instead of tying the backlight directly to V+ and GND, connect it to a PWM pin (you may need to use a separate driver if the pin cannot source/sink enough current). This will allow you to control the brightness via `analogWrite()`.

Turn the LCD display off (`LiquidCrystal::noDisplay()`) when not actively in use. The contents will remain in memory but the LCD segments will not be driven.

Set the various bits in the `PRR` register to disable any peripherals not it use.

And *don't forget to sleep the CPU when it doesn't need to run*. See the "Power Management and Sleep Modes" section of the datasheet for more information about this and the `PRR` register, as well as the `<avr/sleep.h>` documentation for AVR Libc.

body:
Place a transistor in series with a 33R resistor between the LCD pin 16 (backlight ground) and GND and switch the transistor on and off with a digital pin. That way you'll be able to turn the backlight on and off.

You can have a finer control over brightness if you put a PWM pulse on said pin. Just call `analogWrite(D3, value)` where `value` is the desired brightness.

The schematics is below. It's from [Freetronics 16x2 LCD SHield](http://freetronics.com/16x2lcd).

![LCD Brightness control][1]

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


body:
I have a project that I'm currently working on. We have built a green wall, wich consists of plants on a wall

![Green wall][1]

Now, we have a pump situated at the bottom that waters all the plants. There is an arduino board that decides when to put the pump on. Powering it is a solar panel and wind turbine. We want to know how much energy we have saved by using the solar panel and turbine.

**Question:**

How do I measure the amount of energy, in Wh, used from 00h00 that day? Is there a library? Or is this not possible with Arduino?

Thanks a lot.

**To clear up some things**

No, the pump is not fueled directly by the Arduino pin. We are using a motor shield.

Yes, there is an accumulator in the circuit. The solar and wind power recharge a battery which in turn powers the components.

I would like to know the entire energy consumed, not just the pump.

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

title: How to measure total energy usage of an arduino board

Answers: 3

body:
In order to calculate the amount of energy you have to calculate the power first.

The relation is

Energy = (Power * Time of usage)

How to calculate the power?

The voltage for each device in the system is constant. What changes is the current withdrawal in each component in the project.
The main thing you have here is the pump and how much does it consume current.
Usually, you will have on the "plate" of the pump the current withdrawal of it.

Say it consumes 2 Amps.
If that is not available there, use a DMM "Digital Multimeter" and connect in series with the pump and measure the amount of current.

If there are any other major/important components in your project just calculate the current withdrawal from them.

Now add up all the currents and say you ended up with 2 Amps.

If all the components are operating at the same voltage, just multiply the total amount of current withdrawal by the voltage.
WHY?
Because:
P(power) = V(voltage)   * I(current)

If not, just find the power of each component.
Add up all the powers of all you components.

Now you will only have to calculate the energy.

E(Energy) = Power * time

Time here refers to how long is your system working?
Is it a full day, couple of hours. IT doesn't matter. Usually to make things easier use time (in terms of hours).

Say your power ended up with 3kW *kilo Watt*
You've run the system for 2 hours every day
Energy = 3 * 2 = 6 kWh

If you've kept this for a full month.
Energy save in a month = 180kWh.

Just find out how much do the ministry cost for each kWh, and you'll know how much money you've saved!

body:
There are some chip that measure current flow (like ACS714). Just be sure to buy a chip that will not fry under your load, and mount it in serie with the pump. That chip will bring an analog (but there a re "smarter" chip witch use i2c or spi) signal to arduino, using the formula on the datasheet you can find out real (well, as always there are small error) current flow.

You should already know the voltage of the pump, but you can easily read it with a similar chip or even a [voltage divider][1], just pay attention if you are using PWM as if it will fake your reading)

Now, as already pointed out by Adel Bibi, you can multiply the voltage of the pump with the current value readed (find power), multiply with the time elapsed from the last measure and sum up with precedent measure (integral of the power by time)

you can do the same on the wind/solar panel, just invert the sign of the current (as you are Producing and not Consuming power) and voilà!

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

body:
With the accumulator in the system, current draw will increase as that is topped off. The accumulator provides sufficient pressure to drive the system. As system pressure draws down, the pump turns on to bring up the accumulator, with maximum draw nearing cut-off pressure. Taking the total run time of the pump in question (@DLJ) you may chop this up into discrete chunks and measure the draw over those periods, plot that out. I like that greenwall, and I want one. -- Aloha nui loa, MKK
edit -- As an aside, even a 12V pump driving the smallest 1 liter accumulator to 250 kPa, will draw up to 3A for a few moments, given the size of your system. What motor shield are you using?


body:
I would like to know if there is a way to call functions that are contained within C files using an Arduino sketch?

My C file declares and defines a function. To save putting the messy function definition into my Arduino sketch, I'd like to call the function straight from the sketch.

Is there a standard way to do this using Arduino and C?
Here is the sketch:

    #include "crc16.h";

    void setup(){

    }

    void loop(){

      CalculateCRC16("<09M", 4);

    }

and this is the trimmed down C file:

    #include <stdio.h>
    #include <stdint.h>

    uint16_t crctable[256] =
    {
        0x0000, 0x1189,.....

    uint16_t // Returns Calculated CRC value
    CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
        const void *c_ptr, // Pointer to byte array to perform CRC on
        size_t len)        // Number of bytes to CRC
    {

        uint16_t crc = 0xFFFF // Seed for CRC calculation
        const uint8_t *c = c_ptr;

        while (len--)
            crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

        return crc;
    }

title: How to call C functions from Arduino sketch?

Answers: 3

body:
Yes, just copy its declaration line in your sketch:

    extern "C" {
        void myfunction(int arg);
    }

body:
Your CRC function can easily be converted to C++ so that it can go into a *.cpp file. All you need to do is use an explicit cast when you initialise your `c` pointer. Here's the 'proper' C++ way to do it:

    const uint8_t *c = static_cast<const uint8_t*>(c_ptr);

However, an old C-style cast would also work:

    const uint8_t *c = (const uint8_t*)c_ptr;

The problem is basically that C can be a little more permissive about letting you convert pointers implicitly between types. To do it in C++, you need to tell the compiler explicitly that the conversion is intentional.

body:
You can extern "C" #include like the following:

    extern "C"{
    #include "crc16.h"
    };

    void setup(){
    }

    void loop(){
      CalculateCRC16("<09M", 4);
    }

And the crc16.h file could be (some minor fixes, the #pragma once, a cast):

    #pragma once

    #include <stdio.h>
    #include <stdint.h>

    uint16_t crctable[2] ={ 0x0000, 0x1189};

    uint16_t CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
        const void *c_ptr, // Pointer to byte array to perform CRC on
        size_t len)        // Number of bytes to CRC
    {
        uint16_t crc = 0xFFFF; // Seed for CRC calculation
        const uint8_t *c = (const uint8_t *)c_ptr;

        while (len--)
            crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

        return crc;
    }


body:
I have made this small program to lighten up in sequence 8 LEDs, it starts fine, but it stops working after a minute or so and the first 2 LEDs stay permanently ON, its like the chip stoped, here is the code :

    // Initialize an array with all 8 leds
    // and give them the corresponding
    // digital number.
    const byte led[8] = {0,1,2,3,4,5,6,7};

    // the setup routine runs once when you press reset:
    void setup() {

      // initialize all 8 digital I/O pins as outputs.
      for (byte i = 0; i<9; i++) {
        pinMode(led[i], OUTPUT);
      }
      pinMode(13, OUTPUT);
    }

    void left (void);
    void right (void);

    // the loop routine runs over and over again forever:
    void loop() {

      right();
      left();

    }

    void left (void) {
      for (byte i = 0; i<9; i++) {
        digitalWrite(led[i], HIGH);
        delay(50);
        digitalWrite(led[i], LOW);
      }
    }

    void right (void) {
      for (byte i = 8; i>0; i--) {
        digitalWrite(led[i], HIGH);
        delay(50);
        digitalWrite(led[i], LOW);
      }
    }

I am using a very old arduino duemilanove.

title: Program stops working after a minute

Answers: 3

body:
Your loop conditions aren't quite right, which could be resulting in undefined behaviour. I highly doubt it would cause it to stop working spontaneously, but it's possible in theory.

In each loop that counts upwards, you basically need to stop *before* the counter reaches 8. For example:

    for (byte i = 0; i<8; i++) ...

Note that it's `i<8` instead of `i<9`.

The reason is that the array is only 8 elements long, so the indices run from 0 to 7 (inclusive). Currently, your loops are going all the way up to and including 8, which means it's trying to read past the end of your array.

You'll need to fix that in `setup()` and `left()`.

The loop that goes downwards in `right()` is a little more difficult. At the moment, it runs through indices 8 to 1, meaning it has the same problem of reading past the array. However, it also never actually reaches index 0.

It's harder to fix because `byte` is an unsigned type, so you can't use `i>=0` as your condition (as it will never terminate). Personally, I would rewrite the loop to count upwards, but then reverse the index order inside the loop, so that 0 becomes 7, and so on. For example:

    for (byte i = 0; i<8; i++) {
        digitalWrite(led[7-i], HIGH);
        delay(50);
        digitalWrite(led[7-i], LOW);
    }

Like I said, I doubt this will actually solve your problem. It's worth trying though.

body:
You had several problems with your loop conditions.  Arrays are 0 indexed. If we declare `const byte led[8]`, `led[0]` is the first element and `led[7]` is the 8th and last element.

Also, in `void right()`, you declared `i` as a `byte` which is an 8-bit, unsigned number from 0 to 255. While you wrote the conditional to be `i>0`, it needs to be `i>-1` or `i>=0`. So, if we change the coditional and keep `i` as a `byte` the loop would decrement `i` like 8,7,6,5,4,3,2,1,0,255,254... forever.  So instead, `i` should be declared as a `char` which is an 8-bit, signed number from -128 to 127.

    // Initialize an array with all 8 leds
    // and give them the corresponding
    // digital number.
    const byte led[8] = {0,1,2,3,4,5,6,7};

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize all 8 digital I/O pins as outputs.
      for (byte i = 0; i<8; i++) {
        pinMode(led[i], OUTPUT);
      }
      pinMode(13, OUTPUT);
    }

    void left (void);
    void right (void);

    // the loop routine runs over and over again forever:
    void loop() {
      right();
      left();
    }

    void left (void) {
      for (byte i = 0; i<8; i++) {
        digitalWrite(led[i], HIGH);
        delay(50);
        digitalWrite(led[i], LOW);
      }
    }

    void right (void) {
      for (char i = 7; i>=0; i--) {
        digitalWrite(led[i], HIGH);
        delay(50);
        digitalWrite(led[i], LOW);
      }
    }

body:
Thank you guys, its fixed now, i just dont understand why i cant use byte if i do, i>=0, this way i never goes to 255 anyway and if does, it doesn matter, unless im missing something.
Here goes the final working code :

    /*
      Blink
      Turns on all 8 leds in sequence back and forth.

     */

    // Initialize an array with all 8 leds
    // and give them the corresponding
    // digital number.
    const char led[8] = {0,1,2,3,4,5,6,7};
    #define speed 40

    // the setup routine runs once when you press reset:
    void setup() {

      // initialize all 8 digital I/O pins as outputs.
      for (int i = 0; i<8; i++) {
        pinMode(led[i], OUTPUT);
      }
      pinMode(13, OUTPUT);
    }

    void left (void);
    void right (void);

    // the loop routine runs over and over again forever:
    void loop() {

      // Turn off the buzzer on pin 13
      digitalWrite(13, LOW);

      while(1) {
      right();
      left();
      }

    }

    void left (void) {
      for (int i = 0; i<8; i++) {
        digitalWrite(led[i], HIGH);
        delay(speed);
        digitalWrite(led[i], LOW);
      }
    }

    void right (void) {
      for (int i = 7; i>=0; i--) {
        digitalWrite(led[i], HIGH);
        delay(speed);
        digitalWrite(led[i], LOW);
      }
    }


body:
I just got my Arduino UNO and I'm trying to upload the blink example but the upload fails with

    ioctl("TIOCMSET"): Broken pipe
    ioctl("TIOCMSET"): Broken pipe
    avrdude: stk500_recv(): programmer is not responding
    ioctl("TIOCMSET"): Broken pipe

I have tried both Arduino IDE 1.0.1 (which I installed via my package manager) as well as version 1.0.5 which I downloaded from the arduino.cc website. I'm running Ubuntu Linux 12.10 if that makes a difference.

I'd appreciate any and all help in getting my arduino up and running!

title: "Broken Pipe" when uploading to Arduino UNO

Answers: 2

body:
As with any communication error, try these:

 - Disconnect and reconnect the USB cable.
 - Use a different USB cable.
 - Press the reset button on the board.
 - Restart the Arduino IDE.
 - Make sure you select the right board in `Tools ► Board ►`, e.g. If you are using the Duemilanove 328, select that instead of Duemilanove 128. The board should say what version it is on the microchip.
 - Make sure you selected the right port in `Tools ► Serial Port ►`. One way to figure out which port it is on is by following these steps:
 1. Disconnect the USB cable.
 2. Go to `Tools ► Serial Port ►` and see which ports are listed (e.g. COM4 COM5 COM14).
 3. Reconnect the USB cable.
 4. Go back to `Tools ► Serial Port ►`, and see which port appeared that wasn't there before.
 - In extreme cases, you may need to [burn the bootloader][1].

Answer adapted from [here][2].

  [1]: https://arduino.stackexchange.com/a/474/37
  [2]: https://arduino.stackexchange.com/a/18/37

body:
## It sounds like you have incorrect drivers or the wrong COM port (USB) selected in the IDE
Both are easy to fix. I'd imagine that it would be the COM port.

![IDE][1]

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

To do this:
> Tools → Serial Port → [COM port... try a few different ones. Also you can use device manager to see which one disappears when you unplug your Arduino]

Few notes on photo:

 #1. The selector for the COM port. Choose which one your board is on.

 #2. That shows the COM port selected and board. I don't have my UNO connected: ignore that the COM port isn't showing up on the menu.


body:
I've seen that there are many resources on programming basis for arduino for people that have some electronics basis or background. Are there similar resources on the opposite? Basics electronics for programmers? Things that cover:

* How to read schematics (different elements that appear there)
* What different pins are used for (yeah, even on a more basic level than [arduino documentation][1])
* General idea of how a protoboard/protoshield works and how to connect components
* General common components (resitors, capacitors...) and when and how to use them...
* Safety rules, what happens when you do something wrong

  [1]: http://arduino.cc/en/Reference/Board#.UzSV3WR5NUk

title: 'Basic electronics' resources

Answers: 2

body:
This is an extract of an [introductory book](http://m.dummies.com/DummiesArticle/Arduino-Projects-For-Dummies-Cheat-Sheet.id-379124.html) that shows basic schematic  components:
![Basic schematic components](https://media.wiley.com/Lux/21/379121.image0.jpg)

body:
# From zero to Arduino (maybe a HOWTO someday?)

Rule zero:

 - Don't overestimate the other Arduino users! They all were not born with this knowledge too.
 - Never be too shy to ask!
 - Making mistakes is ok as long as they trigger learning.

(-: short break :-)

You'll find lots of HOWTOs and other tutorials in the wild wild web.

I assume, the confusing thing is to read them in the wrong order.

Forget your Arduino(s) for a while and start with reading about:

 - General common components (resitors, capacitors...) and when and how to use them...

This will at least partially answer:

 - Safety rules, what happens when you do something wrong
 - How to read schematics (different elements that appear there)

If not already done:

 - Read about ANDs, ORs, NANDs, NORs, FLIPFLOPs...

This will show how their schematic symbols look like.

 - ...compare them to creating the same behaviour by programming (if,
   and (&&), or (||), ...)
 - Have a look at bit operations (&, |, ... on whole number variables.

The programming up to this point can be done on your PC.

After this, dedust your Arduino again and jump into:

 - What different pins are used for (yeah, even on a more basic level
   than arduino documentation)

(Happy end. At least for now.)

(I make this a community wiki answer to invite others to expand this text.)


body:
I have programmed an IR remote control along with an LED and an 8bit 7segment on an Arduino Uno.
the segment displays the number I press via the remote, and the LED turns on and off
here's my code:

    case 16738455:
      Serial.println(0);
      if (oldvalue == results.value){
        on(num0);
        delay(1000);
        on(num00);
        delay(1000);
        oldvalue = results.value;
      }

oldvalue stores the last value pressed, which is the DEC value of the buttons, num0 displays the number zero, and num00 turns all the segments off.
I want the 7segment to blink again when I press the same button again.
Can anyone help me with this?
Thanks

title: 7segment blink when the button is pressed

Answers: 1

body:
A simple solution would be to not worry about blinking as a piece of code, ie. remove those delays (I hate blocking code) and instead, if you are currently receiving a signal from the remote, do not display any number (or display your `num00`). Once the value is received and processed, then display that number.

This way, whilst ever the remote button is down, the display will blank out, and the number will appear as soon as the number is released. If it's the same number, then you will see the number, see a blank display, and then see the same number again. Obviously, if it's a different number, the new number would be displayed.

Since most people would only press the remote button for 100-1500ms, it should give you a nice delay anyway.

Finally, you may encounter some flashing if you process the data so quickly and the remote auto repeats. This could be handy if that number is processed multiple times by the receiving unit. The flashing would indicate that that is the case. If that is undesired, implement a simple state machine.

**edit:** your pastebin code came up whilst I was writing this answer. Having a quick look at your code, I would suggest that in the section:

    if (irrecv.decode(&results)) {
      //receiving data? display nothing
      on(num00);
      digitalWrite(ledPin, HIGH);
      Serial.println(results.value, DEC);
      irrecv.resume();
      delay(100);
      int oldvalue = results.value;
      switch(results.value){
        case 16738455:
          Serial.println(0);
          num2display=0;      // make sure to declare this var somewhere
          //if (oldvalue == results.value){
          //  on(num0);
          //  delay(1000);
          //  on(num00);
          //  delay(1000);
          //} else {   // I think you missed an else here
          //  oldvalue = results.value;
          //}
          //on(num0);
          //delay(1000); // you don't want such large blocking delays
          irrecv.resume();
          break;
        case 16724175:
          Serial.println(1);
          num2display=1;       // add this for each section
          irrecv.resume();
          break;
          . . .
      }
    }
    else{
      digitalWrite(ledPin, LOW);
      on(num2display);
    }

you only set the variable to be displayed, but display `num00`. Then in the else, you can display that number


body:
Is it possible to connect an Arduino to an Android Phone and use it for input/output?
Are connections possible over USB? Or do I need to have a wifi or Bluetooth shield?

title: How to connect Android phone to Arduino?

Answers: 4

body:
The [Arduino ADK](http://arduino.cc/en/Main/ArduinoBoardADK) is meant for that. It combines an Arduino Mega with a USB host chip and port. If you don't want to buy a full Arduino, you can buy a [USB host shield](https://www.sparkfun.com/products/9947). Excellent tutorial for it [here](http://labs.arduino.cc/ADK/Index).

What those do is convert high speed USB signals to SPI, which is readable by a microcontroller. Android has libraries known as the Accessory Development Protocol, which can bridge communication from a phone to the USB and then to a microcontroller.

body:
You bet it's possible. I used a pretty cheap bluetooth module that I got from [Amazon](http://www.amazon.com/gp/aw/d/B0093XAV4U), and wrote an app using the information on the official [Android Developers page](http://developer.android.com/guide/topics/connectivity/bluetooth.html) to connect to the Arduino. There are many guides online telling you how to hook up a module to the pins of the duino.

You can probably get a cheaper module if you look on eBay and don't care how long it takes to arrive, and I think there's at least one app on the Play store for controlling an Arduino if you can make it work for your purpose.

USB connections are probably possible, though I haven't done any of that.

body:
I already had this answer typed up on another question so I thought I'd post it here to help you. I've replaced "tablet" with "phone" for easy reading.

> ## You never mentioned your phone model... or Arduino model ##
>
> There are some phones designed to work with USB flash drives and
> printers. This is called OTG (on the go.
>
> **You need:**
>
>  - A phone supporting OTG
>  - An OTG adapter that fits into your phone's USB slot and is compatible
>  - [The Arduino Uno Communicator App](https://play.google.com/store/apps/details?id=com.primavera.arduino.listener)
>  - Arduino Uno (or clone) [Note: It says that it works with Atmega16U2 or Atmega8U2 programmed as a USB-to-serial converter so I would assume
> that that would cover a few boards more than the Uno.)
>
> Another alternitive is to look into
> [Bluetooth](https://www.google.com/search?q=arduino+bluetooth&qscrl=1&tbm=isch&imgil=WyPC4O05Xn4rhM%3A%3Bhttps%3A%2F%2Fencrypted-tbn2.gstatic.com%2Fimages%3Fq%3Dtbn%3AANd9GcSfTtWqIuN9YYdd90OO_tlxsvLUYhV_pl7NfaMhHDzSRq9N6W9rNA%3B1200%3B1200%3B1soQc4CzMzh0MM%3Bhttp%253A%252F%252Fm.dhgate.com%252Fproduct%252Fjy-mcu-arduino-bluetooth-wireless-serial%252F151048482.html&source=iu&usg=__KyMLS4aeubxJnDaMvprgRgADxAs=&sa=X&ei=1BUCU635IYmEygGO1oHwCQ&ved=0CGkQ9QEwBg&biw=1280&bih=899)
> (Note: I just picked a random link but there are hundreds of similar
> BT adapters)

*[From my answer on a similar question](https://arduino.stackexchange.com/a/272/220)*

body:
You can connect Android and Arduino with usb and use the easy tool App inventor 2 for android

Did you try this new application : https://play.google.com/store/apps/details?id=bp.usbbridge.appinvDemo and full version : https://play.google.com/store/apps/details?id=bp.usbbridge.appinv

Find Videos about Explications : USB OTG Bridge Serial UART for APP Inventor 2 and ARDUBLOCK on youtube


body:
I'm new to arduino. I have nexus duino robot as described in http://www.aliexpress.com/item/3WD-48mm-Omni-Wheel-Mobile-Arduino-Robot-Kit-10019/688287804.html, the shield connected with motors and support xbee.

With simple serial comm sketch, I'm able to communicate between arduino and PC if the shield not inserted, but not if I insert the shield as it seem arduino can't receive serial data (still can send data to PC tough). Someone says that the shield might be use RX TX so it interfere with serial comm.

My Questions are, is there a way to check whether the shield use RX TX? If yes, can we make it not interfere with serial comm? Could be other problem causing this serial comm problem?
Thanks in advance.

title: Shield interfere with Serial Communication

Answers: 1

body:
You really do need to provide information on the shield, there are many versions out there (and I own half of them <G>).

In essence, unless you are using an alternate serial port (`SerialN`) or software serial, then YES, your XBee will be using the same lines as your Arduino. If you are using `Serial.print` or `Serial.write` to talk to the XBee, then that is a giveaway too.

The reason for this is the XBee talks to your Arduino through the serial port, but the Arduino IDE also talks to your Arduino (for programming and `Serial.print`) as well. You can only do one successfully.

In answer to your second question, most likely not. It will be the XBee shield causing you your problems.

edit: I thought I would add, I actually have ONE shield that uses RX and TX but also allows for programming at the same time. This is achieved through a series resistor and (in the case of the shield) an amplifier as well.


body: I have recently designed a shield to my Arduino Duemilanove, which has 8 LEDs, on the digital GPIO, from 0 to 7, but it won't program with the shield on because the voltage drop is too much on the RX and TX lines. My question is: can I have a LED on the TX/RX line with a minimum resistor value that allows me to program the Arduino?

title: LEDs on TX/RX lines interfering with the programmig of the device

Answers: 1

body:
I just found this reference ([using ICSP for output as well as programming][1] -- essentially the same thing), and it suggests a 4.7kOhm.

I didn't have a 4.7k handy, and used a 15k instead and it works.

In my scenario, I have run a sketch with a polarized buzzer connected between RX (digital 0) and `GND`. When connected directly (with no resistor) the sketch fails to load (but the buzzer works as expected).

If I put the resistor in series with it, the sketch uploads without fail.

You also probably realise, but mentioning for clarity/completeness, you will lose all serial port functionality for debugging purposes and won't be able to use `Serial.[anything]`. Make sure to not even initialise the port.

  [1]: http://www.avrfreaks.net/index.php?name=PNphpBB2&file=printview&t=70515&start=0


body:
Have you heard about support for IPv6 protocol for any Ethernet shield?
As far as I know only IPv4 is supported.
Maybe some one would like to write library?

title: Ethernet shield and IPv6 support

Answers: 2

body:
**There is no library, and there physically cannot be one.** IPv4 is built into the Ethernet shield itself. (It has a *Wiznet 510* chip.)

> Shields based on the MicroChip ENC28J60 chip (such as those sold by Ekitszone and Nuelectronics) are suitable for the implementation of an IPv6 or dual IPv4/IPv6 stack. This approach requires the TCP state machine to be implemented in software and results in more complex arduino code.

*Source: [this tutorial](https://www.adafruit.com/blog/2012/09/17/ask-an-educator-how-can-i-get-my-arduino-to-use-ipv6/). (You may find it useful, I'd recommenced reading it.)*

There is [this library for IPv6 on *other hardware*, not for the official Ethernet shield](https://sites.google.com/site/ghoelzl/ipv6ethershield).

body:
I have been working on an IPv6 library for Arduino, called EtherSia, that works with the ENC28J60 chip, but with a lower overhead compared with libraries that use Contiki / uIP. It is comparable to the EtherCard library for IPv4.

https://github.com/njh/ethersia

While the Wiznet chips do not support IPv6 natively, they do have a MACRAW mode that allows you to send Layer 2 Ethernet frames directly. I have managed to get IPv6 working with the Wiznet W5100 and W5500 chips, which is what the official Arduino Ethernet Shield and Ethernet Shield 2 use.

So it is possible...


body:
I tested an [MPU-6050 (GY-521)][1] using an Arduino Nano. I used the I2CDevLib and opened the [MPU6050_DMP6.ino][2] with the Arduino IDE. I opened the [MPUTeapot.pde][3] Processing-file with Processing. A few changes was necessary to make it work:

    MPU6050 mpu;

was changed into:

    MPU6050 mpu(0x68);

Additionally I commented out this line:

    #define OUTPUT_READABLE_YAWPITCHROLL

and uncommented this line:

    #define OUTPUT_TEAPOT

When turning everything on, the arrow (Processing) would turn with 5 degrees/s clockwise around the z-axis (plus a very small amount around the other two axes). After about 20 seconds, it would stop, and turn around the x-axis pretty fast for 3 seconds. Then it would stop. Now, the gyroscope+accelerometer would work perfectly. This happens every time I test it.

This happens only when the gyroscope is perfectly still on the ground. It does not stabilize if I move it around. Only after it is left completely still, it'll stabilize after 23 seconds.

Is this how it should work, or is it a problem with the gyroscope? Could it even be caused by the I2CDevLib? Can anybody else confirm this?

  [1]: http://playground.arduino.cc/Main/MPU-6050#.Uzl8TvldU-0
  [2]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050/Examples/MPU6050_DMP6
  [3]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050/Examples/MPU6050_DMP6/Processing

title: Do gyroscopes purposefully show erroneous data?

Answers: 1

body:
MPU6050 is a chip that has an intenal (closed and unknown) algorith to calculate orientation. Because you ar reading ANGLE, that means you are using that algoritm, and that "time" may be the time needed for the calibration.

what do you have as output on the serial?


body:
Looking at my Arduino Uno R3 board and its [reference design schematic](http://arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf) I noticed that there's a second ICSP 6-pin header. In the schematic, the connector I'm referring to is named ICSP1.

**What's that for?**
What useful things can an average Arduino user like me do with it?

The relevant part of the schematic is below (marked in red).

![Arduino Uno R3][1]

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

title: What's the 2nd ICSP header for in Arduino Uno R3?

Answers: 1

body:
It's for the other MCU on the board.

The main MCU on the Uno is labelled "ZIC1". This is the one that is programmed when you press "Upload" in the IDE. But unlike other Arduinos that use a FTDI chip to connect to the serial port on the main MCU, the Uno uses another MCU instead, labelled "U3" on the left. This MCU runs a small bit of code that acts as a serial port via USB and passes through the bytes to its USART1. This then connects to the USART on the main MCU, where the bootloader on that chip accepts the bytes coming through and writes to flash and EEPROM on the main MCU.

You can use this additional MCU as you would any other, but the only I/O it has available are the USB connection, the SPI connection via its ICSP header, the UART1 connection to both the main MCU and pins 0 and 1, and two LEDs on PD4 and PD5.


body:
I am using a mcp23017 to read button presses for my joystick project and am using the internal pullup to minimize complications. Is there a way to invert all the bits in the uint16_t so i can send the values as normally off?

I'm using [this Adafruit library](https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library).

And the reading code: `uint16_t buttons = mcp.readGPIOAB();`

title: How do I use a i2c port expander to read buttons with pull ups and inverting the resulting uint16_t?

Answers: 1

body:
The inversion operator in C++ is `~`.

    Serial.print(buttons, BIN);
    Serial.print(~buttons, BIN);


body:
Following on from https://arduino.stackexchange.com/questions/986/whats-the-2nd-icsp-header-for-in-arduino-uno-r3 I was wondering how this could be hacked to our advantage.

For example, could that firmware be rewritten to have the UNO recognised as a mouse/keyboard input? Could this be done after the boot loader process and leave the uploading process in tact?

Given the limited IO, it seems it's functions might be limited. Plus I have no idea how much code is space is available.

title: Can the 2nd MCU on the UNO R3 be used for keyboard emulation?

Answers: 2

body:
Yes, it is possible. using LUFA, you can burn new firmware to the Serial converter. The only problem is that you need to re-burn the USB-Serial converter to upload another program.

Info: http://www.fourwalledcubicle.com/LUFA.php

Specific page: http://mitchtech.net/arduino-usb-hid-keyboard/

body:
The second MCU is similar to that used in the Leonardo, but is smaller and less capable (ATmega16U2 vs. ATmega32U4). It is certainly possible to reprogram it to do what you like, but its limits means that you can have fewer USB "devices" at the same time.

I have not looked at the existing firmware, but it should certainly be possible to add your own custom code into it such that both the normal serial connection to the main MCU as well as your additional code can coexist.


body: I'm working on a project with a joystick and I'm trying to keep everything a simple and low latency as possible. I am reading the pots with the onboard 10bit ADC on the ATmega 32u4 but may be upgrading to either a 16bit ADC or 24 bit ADC. **How can I filter noise out of the signals?**

title: How can I filter out noise from ADC lines without delay or signal change?

Answers: 3

body:
One possible approach is to go for a completely software side solution.

[Microsmooth][1] is a signal processing library that I am working on that is specifically intended for low latency, low memory signal smoothing. It is still in development, but even now, most of the filters work in less than 100 microseconds per call while giving fairly good accuracy and smoothing. Also, the header file allows for simple configuration for certain filter parameters.

  [1]: https://github.com/AsheeshR/Microsmooth

body:
The Atmel ATmega328 datasheet, section 24.6.1, recommends that you drive the analog input pin with an output impedance of 10 KOhm or less. Also, it recommends that you remove high-frequency components with a low-pass filter. (That low-pass is sometimes called an antialiasing filter).

The simplest possible low-pass filter is a resistor and a capacitor.

      +5V                        +5V
       |                          |
    (sensor)---resistor---+---(Arduino)
       |                  |          |
       |            capacitor        |
       |                  |          |
      GND----------------GND--------GND

Contrary to popular belief, it is not possible to make an antialiasing filter in software.

For an initial low-resolution prototype, a quick rule of thumb is to pick the RC time constant at least 10 times as long as the time between samples.

So if you are sampling at around 1000 Samples/second (i.e., a sampling interval of 1 millisecond), then 100 Ohms of resistance and (roughly) 100 uF ceramic capacitor may be adequate.
(The RC time constant here is RC == 100 Ohms x 100 uF = 10 milliseconds).

Many joysticks already have a relatively high output impedance; you'll need to use a resistor with that much less resistance to compensate.
(Sometimes you don't need any additional resistance; but you still need that capacitor between the Arduino analog input pin and the Arduino ground pin).
(Many sensors have an output impedance more than 10 KOhm; people who use them are pretty much forced to use an op-amp chip to get clean signals).

Entire books have been written on signal filtering.
In addition, there are many other techniques for getting higher resolution analog signals, higher speed data collection, and trading off between them --
but they are probably overkill for reading the position of a joystick.

body: The noise from your joystick pots will drown out any resolution over eight bits regardless.  They were designed for the very crude game port on a pc and use a copper wiper on a slab of carbon.  Not a terrible recipe for a noise generator.


body:
I am sending three analog signals through the xbees to be written to analog pins on the receiving side so they can be read in Simulink. I connected both of the arduino megas to my laptop and uploaded the sketches. I have a shield and a series one xbee connected to each arduino. I pulled up the serial monitor for each sketch. I connected a 1 volt DC power supply to all three analog pins. On the transmitting serial monitor I got numbers close to 200 which I believe is correct but on the receiving side I was not getting anything. I believe the problem is with the arduino. After I uploaded the code on the transmitting side the TX led was green but the RX led on the receiving side was not lit up at all. The power LED on the transmitting arduino is red but it is green on the receiving side. The 'L' led on the transmitting side is red on the transmitting side is read and yellow on the receiving side. On both of the xbee shield the power led's are red and the DIO5 led blinks green. On the receiving xbee shield the DOUT LED is red and the DI LED is green. If more information is needed let me know.

Here is my configuration for the xbees: (series 1. firmware version: 10ed)

Transmitting Xbee:

PAN ID: 1234

MY:10

DL:11

Receiving Xbee:

PAN ID: 1234

MY: 11

DL: 10

Transmitting arduino program:

    int val1 = 0;
    int val2 = 0;
    int val3 = 0;
    int analogPin1 = 0; //these are you analog in pins
    int analogPin2 = 1;
    int analogPin3 = 2;
    void setup()  {
      Serial.begin(9600);  //start serial
    }
    void loop()                               // run over and over again
    {
            Serial.print("<");                // This character signifies the begining of our data cycle
                val1 = analogRead(analogPin1);    // read the input pin
            Serial.println(val1);             // output the signal
            Serial.print("\t");               // Signifies end of 1st piece of data
                val2 = analogRead(analogPin2);    // read the input pin
            Serial.println(val2);             // output the signal
            Serial.print("\t");               // Signifies end of 2nd piece of data
                val3 = analogRead(analogPin3);    // read the input pin
            Serial.println(val3);             // output the signal
            Serial.print(">");                // This character signifies the end of our data cycle
            delay(100);
    }

Receiving Arduino program:

    #include <SoftwareSerial.h>
    // software serial #1: TX = digital pin 0, RX = digital pin 1
    SoftwareSerial portOne(0,1);
    int Apin1 = 0; // These variables hold the current incoming value
    int Apin2 = 0;
    int Apin3 = 0;
    int AnalogOut1 = 0;  //Set our analog pins
    int AnalogOut2 = 1;
    int AnalogOut3 = 2;
    int Digits = 0; // Helps watch for comma
    int Mode = 0; // This designates which section of reading we are doing - begin = 0, Apin1 = 1, Apin2 = 2, APin3 = 3, end = 4
    void setup()
    {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
      // Start each software serial port
      portOne.begin(9600);
    }
    void loop()
    {
      portOne.listen();
      while (portOne.available() > 0) {
      // read the incoming byte:
        char inByte = portOne.read();

        if (isdigit(inByte) && Mode == 1) {
        int temp = inByte - '0';
        Apin1 = (Apin1 * 10) + temp;
        Serial.print('\n'); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
        Serial.print(temp);
        Serial.print('\n');
        Serial.print(Apin1);
        Serial.print('\n');
        }
       if (isdigit(inByte) && Mode == 2) {
        int temp = inByte - '0';
        Apin2 = (Apin2 * 10) + temp;
        Serial.print(temp); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
        Serial.print('\n');
        Serial.print(Apin2);
        Serial.print('\n');
        }
      if (isdigit(inByte) && Mode == 3) {
        int temp = inByte - '0';
        Apin3 = (Apin3 * 10) + temp;
        Serial.print(temp); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
        Serial.print('\n');
        Serial.print(Apin3);
        Serial.print('\n');
        }
        if (inByte == ',') {
        Mode++;
        }
        if (inByte == '<') {
        Mode = 1;
        }
        if (inByte == '>') {
        Mode = 4;
        if (Apin1 > 0 && Apin2 > 0 && Apin3 > 0) {
        analogWrite(AnalogOut1, Apin1);
        analogWrite(AnalogOut2, Apin2);
        analogWrite(AnalogOut3, Apin3);
        }
        Serial.print('\n'); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
        Serial.print(Apin1);
        Serial.print('\n');
        Serial.print(Apin2);
        Serial.print('\n');
        Serial.print(Apin3);
        Serial.print('\n');
        Apin1 = 0; // These variables hold the current incoming value
        Apin2 = 0;
        Apin3 = 0;
              }
        }
    }

title: Problem with Xbee or Arduino?

Answers: 1

body:
The problem is the same as last time (https://arduino.stackexchange.com/questions/843/xbeearduino-communication-problem?rq=1)

You are sending the data via:

    Serial.println(val1);

which outputs an `ASCII` representation of the number.

But in your reading, you are reading in a `byte` value. Actually, I just realised you are reading in a `char` which is a signed (-128 to 127) value:

    char inByte = portOne.read();

first, change that to:

    byte inByte = portOne.read();

Now, you have three options:

1. If (as you say) the numbers you expect are around `200` and will **always** be below `256` (and positive) then you could send a byte value instead. That way, when you read the byte in, you get the same value. You would do this using `Serial.write(val1);` instead of `print`.

2. If you need to send larger than a byte value, eg `int`, then send as two bytes, HIGH and LOW. Then on the receiving end, take in two bytes when reading that data.

3. Send as plain text but read in as plain text. Since you have delimiters, keep reading in the serial until you have all the data you need and then break it down. (You could adapt the code I posted in the answer above to do that).

**edit:** a couple of other points with your code:

- You're doing an `analogWrite` to digital pins `0, 1,` and `2`. Was that your intention? `analogWrite` is reserved for sending out PWM signals on only those pins that are capable (see: http://arduino.cc/en/Reference/analogWrite )

- `analogRead` will read a value of `0-1023` and if your intention is to just use PWM at the other end, then step it down to a value of `0-255`. In that case you can get away with writing byte values to `Serial.write`.

- You're never setting the `pinMode` of the outputs in the receiver.

- You're sending `val1`, `val2`, and `val3` out via `Serial.println` which will send your value out (as `ASCII`), followed by a newline, so the bytes sent from that one line will be `32 30 30 0D 0A`. You have to interpret that at the other end.

- You're also using software serial on the hardware serial port (you're assigning digital pins 0 and 1. These are the hardware serial pins). **BUT** you're also initialising it via hardware serial. I'm guessing that it really wouldn't matter (if the pins are aligned), but you can't expect to receive data via software serial and send data via hardware serial if they're all using the same pins.


body:
The [Arduino LiquidCrystal library][1] has 4 constructors with different arguments:

    LiquidCrystal(rs, enable, d4, d5, d6, d7)
    LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
    LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
    LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

The following comments are stated for the constructor arguments:

> [...] d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using only the four data lines (d4, d5, d6, d7).

What is the point of `d0-d3` if they are not needed? Will they decrease the response time?

  [1]: http://arduino.cc/en/Reference/LiquidCrystalConstructor

title: What is the point of D0-D3 on LCD?

Answers: 3

body:
The answer is on the same page as the quote you mentioned (I have highlighted the important statement):

> Creates a variable of type LiquidCrystal. **The display can be controlled using 4 or 8 data lines**. If the former, omit the pin numbers for d0 to d3 and leave those lines unconnected. The RW pin can be tied to ground instead of connected to a pin on the Arduino; if so, omit it from this function's parameters.

It turns out that the Hitachi HD44780 LCD display can work in 4-bit or 8-bit modes.

body:
That type of LCD has two main modes of operation: 4-bit mode which uses 4 data pins (d4-d7), and 8-bit mode which uses all 8 data pins (d0-d7).

4-bit mode has the advantage of requiring fewer output pins on your Arduino. However, it means your sketch needs to send each command/character as two separate batches of 4-bits (one after the other). This is handled for you automatically by the LiquidCrystal library, so you won't need any extra complexity in your code. However, it does mean that your sketch requires roughly double the number of processor cycles to send anything to the LCD.

In contrast, 8-bit mode sends each command/character as a single batch of 8-bits. That simply means it technically runs a little faster.

With that said, a person looking at the display probably won't see a significant speed difference most of the time, as it still goes very quickly. The main impact will be on the microcontroller (the Arduino in this case). If it can use the faster 8-bit mode then it can devote a little more processing time to other things. That can be particularly helpful for timing-critical applications.

body:
The presence of those pins is a requirement of the technique that had to be used to interface the LCD to the microprocessors that were available back when the HD44780U controller chip was developed.

Single chip microcontrollers as we know them were still in the future and the LCD had to be interfaced to the 8-bit microprocessor chips of the times using the same techniques as any other 8-bit I/O or memory device which was an 8-bit bus.


body:
I'm [debugging a couple of RS232-to-TTL converter boards](https://electronics.stackexchange.com/q/104466/29792) that I'm trying to use to program my Arduinos and one thing I would like to try would be to reduce the upload serial speed from 115200 to 19200.

**How do I do that?**

I imagine that there's a setting that can be easily changed on the Arduino IDE preferences. But where is it? But then the bootloader speed would have to match that? **How do I change the serial upload speed on optiboot, too?**

title: How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE?

Answers: 1

body:
On Arduino IDE side, the upload speed is coded in `hardware/arduino/boards.txt`

    uno.upload.speed=115200
    ...

for every kind of board; you cannot change it directly from the IDE (that would be too dangerous as that value must match the **expected speed for the actual bootloader** of every board).

Now as per the optiboot loader side, the upload speed is defined in `BAUD_RATE` macro, in `optiboot.c`:

    /* set the UART baud rate defaults */
    #ifndef BAUD_RATE
    #if F_CPU >= 8000000L
    #define BAUD_RATE   115200L // Highest rate Avrdude win32 will support
    #elsif F_CPU >= 1000000L
    #define BAUD_RATE   9600L   // 19200 also supported, but with significant error
    #elsif F_CPU >= 128000L
    #define BAUD_RATE   4800L   // Good for 128kHz internal RC
    #else
    #define BAUD_RATE 1200L     // Good even at 32768Hz
    #endif
    #endif

So I guess you can:

1. `#define BAUD_RATE 19200` before that block of code
2. recompile the optiboot loader
3. upload your own new bootloader version
4. update `uno.upload.speed` accordingly in `boards.txt`
5. check it on the usual blink sketch and cross your fingers :-)

Please note that this kind of task is not for beginners, you need to know what you're doing.
Also note that I disclaim any responsibility if you get unable to upload programs to your Arduino afterwards!


body:
The Arduino Uno has an ICSP header that I imagine is for programming the board using a separate ICSP programmer. That is, its ICSP header turn the board into a target.

**Can one use that same ICSP to program other boards, turning the Arduino Uno effectively into a ICSP AVR programmer? How?**

I'm assuming that the target boards would also be Arduinos and wanted the Uno to program them using the Arduino IDE. Is that possible?

Reading the [AVR In-System Programming Application Note](http://www.atmel.in/Images/doc0943.pdf) it looks to me that the only issue would be to make the programmer (the Arduino Uno) control the target board reset line. I've seen something like that in ArduinoISP sketch, but in that sketch, the target reset is controlled by port D10. But one could program the reset line to be an output, right? So could we change the ArduinoISP sketch to use its own reset line as output to control the target board reset line? If not, **why not?**

title: Can the Arduino Uno become an AVR programmer and use the ICSP header to program the target board

Answers: 4

body:
Yes you can program the Arduino's reset input pin as an output and use that to program another AVR, but you can no longer program your Arduino as that relies on the controller being reset through its own reset pin.

Coming to think about it, I am not sure how the other devices (like the USB controller) responds to being reset by Arduino's controller itself. It resets the USB controller which may or may not reset the connection to the computer, possibly loosing data. With the USB controller being reset, GPIO-pins D0 and D1 (the serial interface between PC and Arduino's AVR) may corrupt the datastream.

body:
First of all, as configured, the RESET pin can **not** be used as an output pin. In order to use it as an I/O pin, you would have to program the RSTDISBL fuse. But once you do that, as jippie said, it becomes near-impossible to reprogram your Arduino (if you have the socketed through hole variety of the MCU, you could pull it out and put it into a high voltage programmer; in all other cases, it's effectively impossible).

So in theory, you can use the ICSP header the way you suggest. In practice, it's under almost any conceivable circumstance a terrible idea.

body: I recommend going out and buying an AVR Dragon - costs aroud $US50. That gives you ISCP programming plus debugwire debugging (using the Atmel Studio IDE).

body:
To answer my own question, just to report that I found something close to what I was looking for, which I link and describe briefly below.

[Gammon Software Solutions forum - Atmega Bootloader Programmer - Programming Cable](http://www.gammon.com.au/forum/?id=11635)

On that page, the author suggest that we cut pin 5 from the 6-pin ICSP programming cable, solder a pin to it, and wire it to pin D10. Like so:

![Modified ICSP programming cable][1]

Then, you can load the Arduino Uno with the ArduinoISP sketch and program the target board as usual.

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


body:
I have a CC3000 wifi module from adafruit that is working OK. Now, I am trying to use it together with an external service, which code requires me to pass a Client (from Arduino SDK) reference, but the Adafruit_CC3000_Client does not inherit from Client nor WifiClient.

I am looking for an appropiate wrapper, but unable to find one. Does anyone know about such wrapper?

title: Client or WiFiClient wrapper for adafruit CC3000 wifi

Answers: 1

body:
As I didn't get any answer, and further search for an existing solution failed, I decided to roll my own. The class header is very straightforward, I decided to go for single inheritance and composition of Adafruit_CC3000_Client:

    class CC3000Client: public WiFiClient {
    public:
        CC3000Client(Adafruit_CC3000& cc, Stream& stream=Serial);
        virtual ~CC3000Client();

        virtual int connect(IPAddress ip, uint16_t port);
        virtual int connect(const char *host, uint16_t port);
        virtual uint8_t connected();
        virtual int available();
        virtual void stop();
        virtual void flush();
        virtual int peek();
        virtual int read();
        virtual size_t write(uint8_t v);
        virtual size_t write(const uint8_t *buf, size_t size);
        virtual int read(uint8_t *buf, size_t size);
        virtual operator bool();

    private:
        Adafruit_CC3000& cc3000;
        Adafruit_CC3000_Client client;
        bool peeked;
        int peeked_byte;
        Stream& stream;
    };

The implementation is a bit tricky (or I didn't manage to find a better way), as the Adafruit client does not have peek() functionality, so this wrapper class have to implement it.

    CC3000Client::CC3000Client(Adafruit_CC3000& cc, Stream& stre) :
            cc3000(cc), peeked(false), stream(stre), peeked_byte(0) {
    }
    CC3000Client::~CC3000Client() {
    }

    int CC3000Client::connect(IPAddress ip, uint16_t port) {
        client = cc3000.connectTCP((uint32_t) ip, port);
        peeked = false;
        if (client.connected())
            return 1;
        return 0;
    }
    int CC3000Client::connect(const char *host, uint16_t port) {
        uint32_t ip = 0;
        if (!cc3000.getHostByName((char*) host, &ip)) {
            stream.println(F("Couldn't resolve!"));
            return 0;
        }
        client = cc3000.connectTCP(ip, port);
        peeked = false;
        if (client.connected()) {
            return 1;
        }
        return 0;
    }
    uint8_t CC3000Client::connected() {
        return (uint8_t) client.connected();
    }
    int CC3000Client::available() {
        if(peeked)
            return 1;
        return (int) client.available();
    }
    void CC3000Client::stop() {
        peeked = false;
        flush();
        while (client.connected()){
            client.close();
            delay(10);
        }
    }
    void CC3000Client::flush() {
        peeked = false;
        while (connected() && available())
            read();
    }
    int CC3000Client::peek() {
        if (!peeked) {
            if (available()) {
                peeked_byte = read();
                peeked = true;
            } else
                return -1;
        }
        return peeked_byte;

    }
    int CC3000Client::read() {
        if (peeked) {
            peeked = false;
            return peeked_byte;
        }
        return (int) client.read();
    }
    size_t CC3000Client::write(uint8_t v) {
        return (size_t) client.write(v);
    }
    size_t CC3000Client::write(const uint8_t *buf, size_t size) {
        return client.write(buf, size);
    }
    int CC3000Client::read(uint8_t *buf, size_t size) {
        if(peeked){
            buf[0]=peeked_byte;
            peeked=false;
            return client.read(buf+1, size-1);
        }
        return client.read(buf, size);
    }
    CC3000Client::operator bool() {
        stream.println("Error, bool() not implemented");
        return true;
    }

Both files are available [here][1], if you are using [biicode][2] all you have to do in your code is to put an include like the following and run "bii find", that will also retrieve and install the cc3000 library:

    #include "diego/ardunet/cc3000client.h"

I have used and tested it with a simple http_get call (also [here][1]) and with the [temboo][3] service, and it has worked OK for sending emails from a Gmail account from an Arduino Mega2560 connected to the CC3000. This temboo service uses via the SDK Client interface most methods of this wrapper, but the bool() operator and the CC3000Client::write(const uint8_t *buf, size_t size) method.

  [1]: https://www.biicode.com/diego/blocks/diego/ardunet/branches/master
  [2]: http://www.biicode.com
  [3]: http://www.temboo.com