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

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

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!


sender: user

sender: assistant

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?


message:
How to call C functions from Arduino sketch?

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;
    }

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;
    }


message:
Program stops working after a minute

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.

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


message:
"Broken Pipe" when uploading to Arduino UNO

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!

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.


message:
'Basic electronics' resources

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

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


message:
7segment blink when the button is pressed

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

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


message:
How to connect Android phone to Arduino?

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?

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


message:
Shield interfere with Serial Communication

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.

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.


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

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?

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


message:
Ethernet shield and IPv6 support

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?

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


message:
Do gyroscopes purposefully show erroneous data?

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

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?


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

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

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.


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

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

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

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


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

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.

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.


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

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?**

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.


message:
Problem with Xbee or Arduino?

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;
              }
        }
    }

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.


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

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

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.


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

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?**

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!


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

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?**

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


message:
Client or WiFiClient wrapper for adafruit CC3000 wifi

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?

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


message:
Nothng Written to Serial when using sprintf

I'm using `sprintf` to use a format specifier `myTemplate` with some strings. The result will then be written to Serial. Although the sketch compiles fine, it does not write any thing to the serial, nothing is seen in the Serial monitor.

Is `sprintf` being used wrongly here?

 char* result;
 char* myTemplate;

 void setup() {
   // put your setup code here, to run once:
     Serial.begin(9600);
 }

 void loop() {
     myTemplate = "Welcome %s. You have slept %s times";
     sprintf(result, myTemplate, "Jane", "many");
     Serial.println(result);
     Serial.println("hello");

 }

----------

When I try the follwing sketch and write something to the Serial monitor, I receive gibberish echoed back to me!  Why is this?

**Sketch**

 char received;
 char* message = "";

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

 void loop() {

     // Echos back
     if(Serial.available() > 0) {
         received = Serial.read();
         Serial.println(message);

         if(received == '\n') {
             message = "";
         }  else {
             message += received;
         }

     }
 }

body:
When you use `sprintf()`, you need to have some space allocated for it to write the result to. At the moment, you're just passing an uninitialised pointer (`result`), meaning the behaviour of `sprintf()` is undefined. It might appear to work under some circumstances, but not others (and even if it did seem to work, it could have some nasty side effects on other parts of your code).

The simplest approach is to allocate a static `char` buffer. You need to be sure it's big enough to contain all of the text you want it to store though (plus an extra null character at the end).

For example:

    char* myTemplate = "";
    char result[64] = {0};

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

    void loop() {
        myTemplate = "Welcome %s. You have slept %s times";

        sprintf(result, myTemplate, "Jane", "many");
        Serial.println(result);
        Serial.println("hello");
    }

As a side note, it's usually a good idea to initialise your variables. This is especially true for pointers.


message:
Arduino Uno R3 ISR does not work on pin 2?

I have an Arduino Uno R3. I have a paddlewheel waterspeed sensor that I use on an ISR on pin 2. The power supply is approximately 8v stepped down to 4.92v with a circuit yanked from the phone charger. I have also tried this with the arduino 5v.

The pin returns the correct values with digitalRead(), so it's cycling between 1 and 0.

The ISR works fine on pin3. Why does it work on pin 3 and not pin 2 ISR?

    void itest() {
        Serial.println( "test" );
    }

    void setup() {
        attachInterrupt(0, itest, FALLING);
    }

body: never use Serial inside an interrupt handler, increment a (volatile) variable and print it in the loop().


message:
How do I split an incoming string?

I am sending a list of servo positions via the serial connection to the arduino in the following format

    1:90&2:80&3:180

Which would be parsed as:

`servoId : Position & servoId : Position & servoId : Position`

How would I split these values up, and convert them to an integer?

body:
You can use [`Stream.readStringUntil(terminator)`][1] passing a different terminator for each part.

On each part you then call [`String.toInt`][2]

  [1]: http://arduino.cc/en/Reference/StreamReadStringUntil
  [2]: http://arduino.cc/en/Reference/StringToInt


body:
You could do something like the following, but please take into account several things:

If you use ```readStringUntil()```, it will wait until it receives the character or timeouts. Thus, with your current string, the last position will last a little longer, as it has to wait. You can add a trailing ```&``` to avoid this timout. You can easily check this behavior in your monitor, try to send the string with and without the extra ```&``` and you will see such timeout delay.

You actually do not need the servo index, you can just send your string of positions, and get the servo index by the value position in the string, something like: ```90&80&180&```. If you use the servo index, maybe you want to check it (convert to ```int```, and then match the loop index i) to ensure that nothing went wrong with your message.

You have to check that the returning string from ```readStringUntil``` is not empty. If the function timeouts, you didn't receive enough data, and thus any attempt to extract your ```int``` values will produce strange results.

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

    void loop() {
     for(int i=1; i<=3; i++) {
      String servo = Serial.readStringUntil(':');
      if(servo != ""){
       //here you could check the servo number
       String pos = Serial.readStringUntil('&');
       int int_pos=pos.toInt();
       Serial.println("Pos");
       Serial.println(int_pos);
      }
     }
    }


body:
Contrarily to other answers, I'd rather stay away from `String` for the following reasons:

- dynamic memory usage (that may quickly lead to **heap fragmentation** and **memory exhaustion**)
- **quite slow** due to construction/destruction/assignment operators

In an embedded environment like Arduino (even for a Mega that has more SRAM), I'd rather use **standard C functions**:

 - [`strchr()`][1]: search for a character in a C string (i.e. `char *`)
 - [`strtok()`][2]: splits a C string into substrings, based on a separator character
 - [`atoi()`][3]: converts a C string to an `int`

That would lead to the following code sample:

<!-- language: c -->

    // Calculate based on max input size expected for one command
    #define INPUT_SIZE 30
    ...

    // Get next command from Serial (add 1 for final 0)
    char input[INPUT_SIZE + 1];
    byte size = Serial.readBytes(input, INPUT_SIZE);
    // Add the final 0 to end the C string
    input[size] = 0;

    // Read each command pair
    char* command = strtok(input, "&");
    while (command != 0)
    {
        // Split the command in two values
        char* separator = strchr(command, ':');
        if (separator != 0)
        {
            // Actually split the string in 2: replace ':' with 0
            *separator = 0;
            int servoId = atoi(command);
            ++separator;
            int position = atoi(separator);

            // Do something with servoId and position
        }
        // Find the next command in input string
        command = strtok(0, "&");
    }

The advantage here is that no dynamic memory allocation takes place; you can even declare `input` as a local variable inside a function that would read the commands and execute them; once the function is returned the size occupied by `input` (in the stack) is recovered.

  [1]: http://www.cplusplus.com/reference/cstring/strchr/
  [2]: http://www.cplusplus.com/reference/cstring/strtok/
  [3]: http://www.cplusplus.com/reference/cstdlib/atoi/


body:
This function can be used to separate a string into pieces based on what the separating character is.

    String xval = getValue(myString, ':', 0);
    String yval = getValue(myString, ':', 1);

    Serial.println("Y:" + yval);
    Serial.print("X:" + xval);

Convert String to int

    int xvalue = xvalue.toInt(xval);
    int yvalue = yvalue.toInt(yval);

This Chunk of code takes a string and separates it based on a given character and     returns
The item between the separating character

    String getValue(String data, char separator, int index)
    {
        int found = 0;
        int strIndex[] = { 0, -1 };
        int maxIndex = data.length() - 1;

        for (int i = 0; i <= maxIndex && found <= index; i++) {
            if (data.charAt(i) == separator || i == maxIndex) {
                found++;
                strIndex[0] = strIndex[1] + 1;
                strIndex[1] = (i == maxIndex) ? i+1 : i;
            }
        }
        return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
    }


body:
 String getValue(String data, char separator, int index)
 {
  int maxIndex = data.length() - 1;
  int j = 0;
  String chunkVal = "";

  for (int i = 0; i <= maxIndex && j <= index; i++)
  {
   chunkVal.concat(data[i]);

   if (data[i] == separator)
   {
    j++;

    if (j > index)
    {
     chunkVal.trim();
     return chunkVal;
    }

    chunkVal = "";
   }
   else if ((i == maxIndex) && (j < index)) {
    chunkVal = "";
    return chunkVal;
   }
  }
 }


body:
**See example at:**
https://github.com/BenTommyE/Arduino_getStringPartByNr

    // splitting a string and return the part nr index split by separator
    String getStringPartByNr(String data, char separator, int index) {
        int stringData = 0;        //variable to count data part nr
        String dataPart = "";      //variable to hole the return text

        for(int i = 0; i<data.length()-1; i++) {    //Walk through the text one letter at a time
            if(data[i]==separator) {
                //Count the number of times separator character appears in the text
                stringData++;
            } else if(stringData==index) {
                //get the text when separator is the rignt one
                dataPart.concat(data[i]);
            } else if(stringData>index) {
                //return text and stop if the next separator appears - to save CPU-time
                return dataPart;
                break;
            }
        }
        //return text if this is the last part
        return dataPart;
    }


body:
Simplest solution is to use [sscanf()][1].

      int id1, id2, id3;
      int pos1, pos2, pos3;
      char* buf = "1:90&2:80&3:180";
      int n = sscanf(buf, "%d:%d&%d:%d&%d:%d", &id1, &pos1, &id2, &pos2, &id3, &pos3);
      Serial.print(F("n="));
      Serial.println(n);
      Serial.print(F("id1="));
      Serial.print(id1);
      Serial.print(F(", pos1="));
      Serial.println(pos1);
      Serial.print(F("id2="));
      Serial.print(id2);
      Serial.print(F(", pos2="));
      Serial.println(pos2);
      Serial.print(F("id3="));
      Serial.print(id3);
      Serial.print(F(", pos3="));
      Serial.println(pos3);

This give the following output:

    n=6
    id1=1, pos1=90
    id2=2, pos2=80
    id3=3, pos3=180

Cheers!

  [1]: http://www.cplusplus.com/reference/cstdio/scanf/


body:
Here is **Arduino** method to split a String as answer to the question ["How to split a string in substring?"](https://arduino.stackexchange.com/questions/31643/how-to-split-a-string-in-substring) declared as a duplicate of the present question.

The objective of the solution is to parse a series of **GPS** positions logged into a **SD card** file. Instead of having a String received from `Serial`, the String is read from file.

The function is `StringSplit()` parse a String `sLine = "1.12345,4.56789,hello"` to 3 Strings `sParams[0]="1.12345"`, `sParams[1]="4.56789"` & `sParams[2]="hello"`.

 1. `String sInput`: the input lines to be parsed,
 2. `char cDelim`: the delimiter character between parameters,
 3. `String sParams[]`: the output array of parameters,
 4. `int iMaxParams`: the maximum number of parameters,
 5. Output `int`: the number of parsed parameters,

The function is based on `String::indexOf()` and `String::substring()` :

    int StringSplit(String sInput, char cDelim, String sParams[], int iMaxParams)
    {
     int iParamCount = 0;
     int iPosDelim, iPosStart = 0;

     do {
            // Searching the delimiter using indexOf()
      iPosDelim = sInput.indexOf(cDelim,iPosStart);
      if (iPosDelim > (iPosStart+1)) {
                // Adding a new parameter using substring()
       sParams[iParamCount] = sInput.substring(iPosStart,iPosDelim-1);
       iParamCount++;
                // Checking the number of parameters
       if (iParamCount >= iMaxParams) {
        return (iParamCount);
       }
       iPosStart = iPosDelim + 1;
      }
     } while (iPosDelim >= 0);
     if (iParamCount < iMaxParams) {
            // Adding the last parameter as the end of the line
      sParams[iParamCount] = sInput.substring(iPosStart);
      iParamCount++;
     }

     return (iParamCount);
    }

And the usage is really simple:

 String sParams[3];
 int iCount, i;
 String sLine;

    // reading the line from file
 sLine = readLine();
    // parse only if exists
 if (sLine.length() > 0) {
        // parse the line
  iCount = StringSplit(sLine,',',sParams,3);
  // print the extracted paramters
  for(i=0;i<iCount;i++) {
   Serial.print(sParams[i]);
  }
        Serial.println("");
 }


body:
    char str[] = "1:90&2:80&3:180";     // test sample serial input from servo
    int servoId;
    int position;

    char* p = str;
    while (sscanf(p, "%d:%d", &servoId, &position) == 2)
    {
        // process servoId, position here
        //
        while (*p && *p++ != '&');   // to next id/pos pair
    }


body:
*jfpoilpret* provided great [answer][1] for parsing serial command on Arduino. However Attiny85 doesn't have bidirectional serial - SoftwareSerial has to be used. This is how you port same code for Attiny85

<!-- language: c -->

    #include <SoftwareSerial.h>

    // Calculate based on max input size expected for one command
    #define INPUT_SIZE 30

    // Initialize SoftwareSerial
    SoftwareSerial mySerial(3, 4); // RX=PB3, TX=PB4

    // Parameter for receiving Serial command (add 1 for final 0)
    char input[INPUT_SIZE + 1];

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

    void loop() {
      // We need this counter to simulate Serial.readBytes which SoftwareSerial lacks
      int key = 0;

      // Start receiving command from Serial
      while (mySerial.available()) {
        delay(3);  // Delay to allow buffer to fill, code gets unstable on Attiny85 without this for some reason
        // Don't read more characters than defined
        if (key < INPUT_SIZE && mySerial.available()) {
          input[key] = mySerial.read();
          key += 1;
        }
      }

      if (key > 0) {
        // Add the final 0 to end the C string
        input[key] = 0;

        // Read each command pair
        char* command = strtok(input, "&");
        while (command != 0)
        {
          // Split the command in two values
          char* separator = strchr(command, ':');
          if (separator != 0)
          {
            // Actually split the string in 2: replace ':' with 0
            *separator = 0;
            int servoId = atoi(command);
            ++separator;
            int position = atoi(separator);
          }
          // Find the next command in input string
          command = strtok(0, "&");
        }
      }
    }

Attiny85 schematics for pin numbers
[![enter image description here][2]][2]

Sketch compiles into:

    Sketch uses 2244 bytes (27%) of program storage space. Maximum is 8192 bytes.
    Global variables use 161 bytes (31%) of dynamic memory, leaving 351 bytes for local variables. Maximum is 512 bytes.

So there is plenty of space and memory for the rest of code

  [1]: https://arduino.stackexchange.com/a/1033/43756
  [2]: https://i.stack.imgur.com/IxwmX.png


body:
    void setup() {
    Serial.begin(9600);
    char str[] ="1:90&2:80";
    char * pch;
    pch = strtok(str,"&");
    printf ("%s\n",pch);

    pch = strtok(NULL,"&"); //pch=next value
    printf ("%s\n",pch);
    }
    void loop(){}


body:
It's not an answer to your question but it may be useful for someone. If your string has a specific prefix, then you can use simply `startsWith` and `substring`. E.g.

    void loop ()
      if(Serial.available()){
        command = Serial.readStringUntil('\n');
        Serial.println("Received command: " + command);
        if(command.startsWith("height")) {
          Serial.println(command.substring(7));
        }
      }
    }

And then send `height 10` what will extract `10`.


message:
Save some arduino pins when driving a 4 digits 7 segments display

I built a simple clock using a 4 digits 7 segments LCD display. I display one digit at a time, switching on and off very quicky and cycling through digits.

Everything is ok, but I used 8 + 4 = 12 arduino pins. I need 2 more pins for other features and I don't want to use 0 and 1 as I need onboard programming features of Arduino Mini.

I used I2C for RTC clock, I could add some interface here (like a PCF8574) and get some pins from here. But I'd like a different (and more educational, for me) approach.

Is there an IC that sends an HIGH output on one of four output pins driven by 2 input pins? I need this:

    IN     OUT
    P0 P1  D0 D1 D2 D3
    0  0   1  0  0  0
    0  1   0  1  0  0
    1  0   0  0  1  0
    1  1   0  0  0  1

This way I can connect OUT to digit selection and spare 2 pins.

Thanks for your hints.

body:
A 2-to-4 line decoder should do what you need. I've used a [74HC139][1] with Arduino before, which contains two decoders in a 16-pin DIP.

There are lots of other options though. In the past, I've used an 8 bit serial-to-parallel shift register ([74HC595][2]) to control a 7 segment display. It effectively lets you control 8 (or more) outputs using only 3 pins on your microcontroller. You have to be careful of power requirements though. Most shift registers aren't able to drive such a display directly, but I was able to incorporate transistors quite easily to get around that.

  [1]: http://www.fairchildsemi.com/ds/74/74VHC139.pdf
  [2]: https://www.sparkfun.com/datasheets/IC/SN74HC595.pdf


body:
An [I2C IO expander][1] might be your best bet.  If your existing I2C device uses a different address, you may be able to put both devices on the same I2C bus.  You would then use 0 additional pins compared to your current design.

  [1]: http://www.digikey.com/product-detail/en/MCP23017-E/SP/MCP23017-E/SP-ND/894272 "I2C"


body:
I know it's not what you asked, but you're using a lot of pins, why not try streamlining them and go to an I2C backpack? [This one from adafruit][1] includes a single 4x7 segment display.

given your comment, another option would be an [I2C/SPI 7 Segment driver][2]. ([datasheet][3]).

new edit: Actually, when I posted the above 7 segment driver, this is the one I was thinking of. I don't know why I didn't find this the first time.

[max7219/7221 datasheet][4] and [digikey source][5]:

  [1]: http://www.adafruit.com/products/879
  [2]: http://uk.farnell.com/nxp/saa1064-n2/ic-led-driver-4dgt-i2c-24dip/dp/1627002
  [3]: http://www.fortito.mx/wp-content/uploads/technical/SAA1064.pdf
  [4]: http://www.maximintegrated.com/datasheet/index.mvp/id/1339
  [5]: http://www.digikey.com.au/product-search/en?vendor=0&keywords=max7219+|+max7221


body:
Are you using your analog pins?  Did you know [they can be used as digital pins][1]?

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

This is your best bet if you aren't using all your analog pins.

  [1]: http://arduino.cc/en/Tutorial/AnalogInputPins


message:
What is the library m in C++ linker?

Following [this guide][1], it says to include a library in the C++ Linker called `m`. What is this for?

Specifically, [Your second Arduino project][2].

4) **Configure project**

5th dot point:
> AVR C++ Linker -> Libraries: Under libraries, add arduino_core and m (in that order). Under path, add the path to the correct core library, e.g. "`${workspace_loc:/arduino_core/328P_16MHz}`"

  [1]: http://playground.arduino.cc/Code/Eclipse#.UzgDN_nEKG4
  [2]: http://playground.arduino.cc/Code/Eclipse#YourSecondArduinoProject

body: The m library is the "math" library. You have to link with it in most flavours of gnu compilers (it is typically not required in other, as it is included in the standard lib) when using functions and stuff from the header file "math.h".


message:
updating firmware on arduino wifi shield

I'm trying to upgrade firmware on my wifi shield by following the [upgrade instructions for Mac](http://arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading). I was wondering what this means?:

> Connect a jumper on the J3 connector, that put the shield in the programming mode. Then connect the USB cable to the shield USB mini socket

**How can I do this?**

body: A "jumper" is a little piece of metal (or a 0-ohm resistor) that connects two pads or pins together. So, create an electrical connection across J3 ("DFU programming jumper" in all the pictures). You will then be able to program the shield via USB.


body:
The jumper is only neccesary if your device is not R3 (revision 3)
Be carefully if you connect the shield and your computer does not
recognice the port.
You gonna need a driver in the link below there are all the steps
include other links to download software as Flip 3.4.7 who has
the executable batchisp which one you can made the changes
read the web site:

http://www.dfrobot.com/community/?p=3760

and extra information about that in official site of arduino
WiFi Shield Firmware Upgrading

there you gonna have an idea how to do it.

for me was more clear as in this site describe everything
and also teach to probe if there is an update
having sucess in the process to installing something it
could be as a question answered with non the specific
thing you need.

http://www.binarytaskforce.com/Weblog/2013/09/21/arduino-wifi-firmware-update/

I am also in the process to update my device if I will have success
I will write to how I do it.
At the moment reading a bunch of differents forums beacuse arduino team itself
appearently had some troubles to provided a guided how to do it sucessfully.


message:
Building Arduino Nano from components

At this stage, my finalized design includes Arduino Nano 3.0, a breakout board and a few electrical components on a breadboard.

Will there be an appreciable cost savings from not buying a ready-made Arduino? The Arduino Nano clone being used costs $17.20.

And is it a good idea if everything is soldered on to a custom fabricated PCB board, including the components of Arduino Nano 3.0? The PCB board will cost around $10 at the quantities I'm starting with.

body:
You can probably do a lot better than $17 but not much better than $8:

http://www.ebay.com/itm/Mini-USB-Nano-V3-0-ATmega328P-5V-Micro-controller-Board-For-Arduino-compatible-/130977189883?pt=LH_DefaultDomain_0&hash=item1e7ed94ffb

If you don't need USB, you can use a Pro Mini and they go for about $4 and that's really hard to beat.


message:
LCDs larger than 20x04 and 5" diagonal

Are there any i2c LCD screens that are larger than 2004 characters and larger than 4.8 x 2.7 x 1.2 inches in dimensions?

I have the [Sainsmart 2004 LCD][1] but it can't display all the information that I need. Maybe a 20x8 character screen? Because the screen will be viewed from a distance of about 50cm, the screen size should be at least 5" in diagonal.

![enter image description here][2]

  [1]: https://www.sainsmart.com/products/20x4-iic-i2c-twi-lcd-module
  [2]: https://i.stack.imgur.com/X6vHl.png

body:
Naked displays... search e.g. Ebay for "40x4 lcd" (maybe enable "worldwide" search)...

...naked... so not i2c ... but Arduino libs for these displays exist (e.g.: [liquidcrystal440][1]), so add an Arduino-Pro or such and you can have i2c... basically they are two 40x2 displays on the same spi bus selected by different chip select lines...

  [1]: https://code.google.com/p/liquidcrystal440/


body: The 44780 display chip used by these devices has 80 bytes of storage, which is why you can scroll the 2x16 side to side to show up to 40 characters per line. however 4x20 is 80 and that's the limit of the chip.


body:
There are ST7920 based displays which may come close to what you are looking for. They have a similar parallel (4 or 8 bit) interface to the HD44780 based displays (as you have been using), but also support a 3-wire SPI-like interface.

A quick google found the datasheet here:
https://www.lcd-module.de/eng/pdf/zubehoer/st7920_chinese.pdf

They have both graphics and text modes, and most of the displays appear to have 128x64 pixels, giving 16x8 characters assuming 8x8 font, although it appears the native text font is 16x8 pixels.

While it might be more complicated to use these in graphics mode, they are probably the closest to the HD44780 based displays in appearance (large monochrome pixels), unlike other large displays which will probably have more (smaller) pixels than you need.

See also https://playground.arduino.cc/Code/LCD12864


message:
How to create a serial communication connection between Cubieboard running Android and Arduino

I am connecting my Arduino to my Cubieboard that is running Android.

I tested this originally with my android tablet and USB cable. This worked successfully for the most part using the firmata kit but I don't want to use firmata.

I want a basic function library written in Java for use with Unity (eg [Library Tutorial Video][1]) to connect to the Arduino via the USB serial port connection much like a connection with my Windows computer.

**I'd like basic command functions like:**

 - Connect / Open
 - Write
 - Read
 - Flush
 - Close

I was thinking maybe of using this library [here][2] but I am unsure how to go about this. I know similar discussion have already taken place on the forum claiming it may not be possible, but it is very clear that it is. It has been done many times. All I need to do is send strings with serial after finding the Arduino's COM port and reading from the serial.

  [1]: https://www.dropbox.com/s/i1mera8850cp6u8/Creating a Simple Unity plugin to Android.mp4
  [2]: https://github.com/mik3y/usb-serial-for-android

body:
Using the library you linked should be a simple case of downloading the library's jar file from https://github.com/mik3y/usb-serial-for-android/releases and adding it as a reference/library/dependency (I forget what eclipse calls them) in your eclipse project.

Then of course providing you connect with the right baud rates and so on it should work.


body:
Totally insane thought here but.....

Have you tried writing a chrome App to talk to your Arduino?

I did it on the Mac - had chrome monitoring things happening on the network and sending Serial Commands to the Arduino over USB.

You can find samples in the Chrome samples / docs

https://developer.chrome.com/apps/serial


message:
Why my Arduino Uno R3 doesn't work with a recompiled optiboot with BAUD_RATE=57600

This is a follow on question from https://arduino.stackexchange.com/questions/1002/how-to-reduce-serial-speed-on-arduino-bootloader-optiboot-and-on-the-ide

I did manage recompile optiboot bootloader to work at 57600 bps and uploaded it to a couple of ATmega328-PUs. I just changed the `BAUD_RATE` to `57600L` in Makefile and recompiled it.

They worked just fine with my [Arduino Single Sided Serial (Severino)](http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3) and a couple of custom standalone Arduino boards with FTDI-like header.

However, I couldn't program the same MCUs using my Arduino Uno R3. When I try to upload a sketch, avrdude just sits there waiting for a response that doesn't come. The output I got is something like this:

    avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\Users\Ricardo\arduino-1.0.5\hardware/tools/avr/etc/avrdude.conf"

             Using Port                    : \\.\COM3
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Recv:
    avrdude: stk500_getsync(): not in sync: resp=0x00

    avrdude done.  Thank you.

Would that have anything to do with the 2nd MCU that acts as the USB driver on the Uno - the [ATmega16U2](http://www.atmel.com/devices/atmega16u2.aspx)? Do I have to patch it, too?

So, my questions are:

**1. Why my recompiled optiboot didn't work with my Arduino Uno R3?**

**2. What can I do to check what's wrong with the upload process using my new bootloader?**

body:
Chris Stratton's comments helped me find a workaround for my problem. It looks like the version of optiboot I was working with (see [source-code here](http://pastebin.com/d8NUirfZ)) doesn't work properly at 57600 BAUD with Arduino Uno without modifications (that I don't know how to make). So I compiled the bootloader with 76800 BAUD, configured the IDE accordingly, and all my boards started to work fine with it.

It is still unclear to me the reason I one can't use 57600 BAUD, but I'm too pragmatic and too little knowledgeable to go after the true answer. So, I'll take Chris' word for it. He said this:

> Basically, 57600 does not divide in 16 MHz nicely when the 8x or 16x oversampling of the hardware UART is taken into account. My gut feeling is that different implementation are using different approximations. If they used the same approximation then even if "wrong" things would be basically fine (especially as the hardware design is similar), but if they are are off in opposite directions it could be unreliable. If you post the exact bootloader source you used we can see for sure - some optiboot source I just looked at seems to actually be using a software UART for 57600.

That's the end of it for me.


message:
What's the difference/relationship between Arduino and AVR?

I'd always thought Arduino was a microcontroller platform but the actual microcontroller is an AVR chip made by Atmel, or something like that made by someone else, based on a RISC ISA, and Arduino is usually used to refer to the whole circuit board powered by this AVR chip. Is my understanding correct?

What's the difference/relationship between Arduino and AVR?

body:
The Arduino is an AVR processor running special code that lets you use the Arduino environment.

AVR's can be used by themselves with some additional supporting components.

Arduino is a combination of both AVR(chip) and breadboard.

AVR is a single chip, and would require a breadboard.


body:
Arduino is a prototyping board, and the term "Arduino" is also used to refer to the IDE and library on the PC side, and the whole ecosystem.
AVR is the architecture (developed by Atmel) of the microcontroller chip used in all official 8-bit boards, and almost all clones.
Arduino UNO and 2009, the most used boards, use the AtMega328P chip.

Many times, Arduino is used to quickly test some idea, sensor, and circuitry, then a stand-alone board is built around the AtMega chip, as it cost 1/10 of the Arduino board, soldered circuit on a stripboard or on a custom PCB are more reitable, and can be optimized on some aspect, like power usage, space occupied, high current/voltage, and so on.

Newest and advanced Arduino board use a different chip with a very different architecture; the Arduino Yun uses a SAM plus a classic AVR, the Due uses an ARM (same architecture used by many smartphones), the Galileo use an x86 (like a classic single-core cpu).


body:
[Arduino is a set of open-sourced hardware- and software specifications, originally conceived as a students' platform.][1] I would add that the specifications, though openly available, are distributed under various public licenses.

There are "official" Arduino boards made by an Italian company of the same name, but as the board designs are open-sourced, there are lots of good (and a few "less good") variants from other sources.

AVR refers to the line of MCUs manufactured by Atmel and used in the original designs. Atmel was acquired in 2016 by Microchip Technology, who continue to manufacture the AVR devices.

Some of the more recent Arduino designs use more capable processors from other chip manufacturers, but many still use the Atmel/Microchip AVR processors. The smaller AVRs' relative simplicity (ATtiny & ATmega, f/ex) make them ideal for quickly designing/building boards and software for less demanding applications and for learning about programming and digital controls.

  [1]: https://en.wikipedia.org/wiki/Arduino#History


body: The Arduino tools and ecosystem supports processors other than just Atmel AVR chips.  For instance the Arduino Due uses an ARM Cortex-M3 processor.


body:
Arduino is really a common set of code that makes using the dev boards they sell accessible to wide range of user base.

Arduino is basically an IDE that uses the C/C++ language and a set of classes that are adaptable to common set of hardware, predominantly Atmel and mostly AVR although as people have mentioned already the Arduino boards are becoming increasingly more powerful. But is amazing how much you can do with the ATmega328p.

You don't have to use the Arduino IDE to program your board and in fact, I tend to use Atmel Studio myself or Notepad++. You can get a plug-in for Atmel Studio 6.2 and above that allows you to create sketches and upload them to most Arduino boards.


message:
Modbus Protocol Compile Error

I have Code for Mod bus Library as below. I have Gone through lots of forum. How to assign device ID, slave address, length using below library function:

    #include <SimpleModbusSlave.h>
    #define  LED 9
    enum
    {

      ADC_VAL,
      PWM_VAL,
      HOLDING_REGS_SIZE // leave this one
    };

    unsigned int holdingRegs[HOLDING_REGS_SIZE];
    void setup()
    {
      modbus_configure(&Serial, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);
      pinMode(LED, OUTPUT);
    }

    void loop()
    {
      modbus_update();
      holdingRegs[ADC_VAL] = analogRead(A0); // update data to be read by the master to adjust the PWM
      analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
    }

I am getting Error has.

    SimpleModbusSlaveArduino.cpp: In function 'void setup()':
    SimpleModbusSlaveArduino:79: error: 'SERIAL_8N2' was not declared in this scope

![Error message for IDE][1]

I have  made changes in the lib as in forum. but I found no value read by my software.

Master sending below request on read mode. But not receiving anything.

    12:31:02.953: Com8, Baud Rate: 9600, Data Bits: 8 Bits, Parity: None, Stop Bits: 1 Stop Bit
    12:31:02.953: Echoback: On, RTS Control: On, Transmit Delay: 5 ms, Response Delay: 1000 ms
    12:31:02.953: Read Holding Register(s), Repeat Loop
    12:31:02.953: Device Address: 01h, Register: 0000h
    12:31:02.953: |-> Read Register: 0000h
    12:31:02.968: -> [01h] [0Dh] [00h] [00h] [00h] [01h] [CBh] [EDh]

![my softawre][2]
[CHANGES MADE IN AS IN FORUM MENTIONED][3]

  [2]: https://i.stack.imgur.com/rJSz8.jpg
  [3]: http://forum.arduino.cc/index.php?topic=176142.0

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

body:
Not sure where you got the library from, but if it's from this [github repo][1], you're using it wrong.

The function prototype for `modbus_configure` is:

    void modbus_configure(long baud, byte _slaveID, byte _TxEnablePin, unsigned int _holdingRegsSize, unsigned char _lowLatency);

The [example file][2] shows how to use it correctly

    modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE);

  [1]: https://github.com/thibs0/EWC2013-Greenhouse-demo/tree/master/Arduino/libraries/SimpleModbusSlave
  [2]: https://github.com/thibs0/EWC2013-Greenhouse-demo/blob/master/Arduino/libraries/SimpleModbusSlave/examples/SimpleModbusSlaveExample/SimpleModbusSlaveExample.ino


body:
In your first example the error is that SERIAL_8N2 is not declared. maybe you are using an old Arduino IDE? try latest 1.0.x or 1.5.x

in the second case TOTAL_REGS_SIZE is a pointer to int, while the function expect a char. Without code is hard to tell what is wrong and how, but in your first code it should be

    modbus_configure(115200, 1, 2, HOLDING_REGS_SIZE);

also because you are not passing a reference to the array, you have to pass a pointer pointing the current element in the update function

    modbus_update(holdingRegs[i]);
    i++


message:
Can I get a Datetime object from a unix timestamp?

Is there a way to get a DateTime object from a unix timestamp and hour offset? I want to be able to print a formatted string, for example `Wed Apr 02 17:15:06 2014`.

I have:

 1. A unix timestamp: `1396451852`.
 2. An offset from my hour zone, `+1` hour.

Note: I get the timestamp from an internet service and want to make the conversion in the Arduino.

body:
The [Arduino Time Library][1] looks like it can do it. Or have a look at the strftime() function from unix and unix-oid environments. There is [source to strftime() here][2]. It's pretty large but you can probably cut it down considerably to just the format parts you need.

  [1]: http://playground.arduino.cc/Code/Time
  [2]: http://www.jbox.dk/sanos/source/lib/strftime.c.html


body:
The seconds since (UNIX) epoch relies on a [database](https://en.wikipedia.org/wiki/Tz_database).

> New editions of the database and code are published as changes warrant, usually several times per year.

Your options can:

- Reduce the timezone database to the timezone you are actually interested in;
- Don't forget about daylight savings time for you specific timezone;
- The leap years are well known too and reasonably easy to program;
- The leap seconds are decided upon usually only couple months before they are introduced and therefore cannot be accounted for in an algorithm.

Conclusion
-
- So can you convert epoch to a time/date format? Yes.
- Will it be accurate? It'll drift away over time (months or years)

Advise
-
If you retrieve epoch from an Internet service, why not use (another?) webserver that has the full timezone database available to convert it to accurate date/time, or 'synchronize' against every once in a while?


message:
Using TIMER0_COMPB_vect

I'm trying to understand how to fully use the COMPB vector ISR of Timer0 on the ATMega328 (standard Arduino core). I realize it will make delay() and millis() not work but that's ok by me. I've setup some test code that *should* output a 244Hz signal on D4 and 488Hz on D5 (note, this is running at 8MHz). But D5 (COMPB) is always what D4 (COMPA) is. Any thoughts? Code below:

    #include <avr/interrupt.h>

    volatile bool stateA = false;
    ISR(TIMER0_COMPA_vect)
    {
     if (stateA)
      PORTD |= _BV(PIND4);
     else
      PORTD &= ~(_BV(PIND4));

     stateA = !stateA;
    }

    volatile bool stateB = false;
    ISR(TIMER0_COMPB_vect)
    {
     if (stateB)
      PORTD |= _BV(PIND5);
     else
      PORTD &= ~(_BV(PIND5));

     stateB = !stateB;
    }

    void setup()
    {
     DDRD |= _BV(PIND4) | _BV(PIND5);

     //set timer0 interrupt at 2kHz
     TCCR0A = 0;// set entire TCCR2A register to 0
     TCCR0B = 0;// same for TCCR2B
     TCNT0 = 0;//initialize counter value to 0
     // set compare match register for 2khz increments
     OCR0A = 255;//244Hz
     OCR0B = 127;//488Hz
     // turn on CTC mode
     TCCR0A |= (1 << WGM01);
     // Set CS01 and CS00 bits for 64 prescaler
     TCCR0B |= (1 << CS01) | (1 << CS00);
     // enable timer compare interrupt
     TIMSK0 |= (1 << OCIE0B) | (1 << OCIE0A);

     interrupts();

    }

**Update:** After thinking about it, I'm realizing that it's not that I need two separate frequencies (though I just kinda wanted to know how, so this is good stuff) but I just need two separate interrupts, only using Timer0 (1 & 2 are already in use elsewhere). They can be the same frequency, most likely. I probably *could* put all the functionality I need in the same TIMER0_COMPA_vect, however I was trying to use that in a library I was writing and was trying to keep the functionality separate... this may not be possible.

body:
Your code doesn't do what you think it does. The timer always runs at 244Hz, and OCR0B only matches twice per period, causing it to have the same frequency but a different phase. What you need to do is set OC0B on compare match and clear it in the overflow ISR. OCR0A you can simply set to toggle on match.

    TCCR0A = _BV(COM0A0) | _BV(COM0B1) | _BV(COM0B0) | _BV(WGM01);
    TIMSK0 |= _BV(OCIE0A);

     ...

    ISR(TIMER0_COMPA_vect)
    {
      PORTB &= ~_BV(PD5);
    }

Also, OC0A is D6, not D4.


body:
I think your code did not set `TIMSK0` properly.

Instead of:

    TIMSK0 |= (1 << OCIE0B) | (1 << OCIE0A);

You should use:

    TIMSK0 = (1 << OCIE0B) | (1 << OCIE0A);

Why? Because `TIMSK0` is already initialized by Arduino libraries before your `setup()` is called.

If you take a look at `hardware/arduino/cores/arduino/wiring.c` and search for the `init()` function, you will see that it contains the following lines:

     // enable timer 0 overflow interrupt
    #if defined(TIMSK) && defined(TOIE0)
     sbi(TIMSK, TOIE0);
    #elif defined(TIMSK0) && defined(TOIE0)
     sbi(TIMSK0, TOIE0);
    #else
     #error Timer 0 overflow interrupt not set correctly
    #endif

With these lines, the `TOIE0` bit of `TIMSK0` is set, but your `setup()` does not clear it.


body:
Actually, after reading the ATmega328P datasheet again, I am not sure that you can use both `OCR0A` and `OCR0B` in normal timer mode.

In particular, since you use CTC mode, I think that `TCNT0` will be cleared every time its value reaches `OCR0A` i.e. 127.

Since you need 244Hz and 488Hz (exactly twice 244Hz), I think you can operate with only one of `OCR0A` or `OCRB0` and do the work in one ISR only:

    #include <avr/interrupt.h>

    volatile bool setBothPins = false;
    ISR(TIMER0_COMPA_vect)
    {
        if (setBothPins)
            // D4 is changed only once (244Hz)for every 2 changes of D5 (488Hz)
            PORTD ^= _BV(PIND4);
        PORTD ^= _BV(PIND5);

        setBothPins = !setBothPins;
    }

    void setup()
    {
        DDRD |= _BV(PIND4) | _BV(PIND5);

        //set timer0 interrupt at 2kHz
        TCCR0A = 0;// set entire TCCR2A register to 0
        TCCR0B = 0;// same for TCCR2B
        TCNT0 = 0;//initialize counter value to 0
        // set compare match register for 2khz increments
        OCR0A = 127;//488Hz
        // turn on CTC mode
        TCCR0A |= (1 << WGM01);
        // Set CS01 and CS00 bits for 64 prescaler
        TCCR0B |= (1 << CS01) | (1 << CS00);
        // enable timer compare interrupt
        TIMSK0 = (1 << OCIE0A);

        interrupts();
    }