message:
Why I cannot change array values even if a statement is successfully called? TFT Touch Screen

#include <Adafruit_GFX.h>    // Core graphics library
    #include "LGDP4535.h" // Hardware-specific library
    #include <zTouchScreen.h>
    #define BOXSIZE   40
    // Assign human-readable names to some common 16-bit color values:
    #define BLACK   0x0000
    #define BLUE    0x001F
    #define RED     0xF800
    #define GREEN   0x07E0
    #define CYAN    0x07FF
    #define MAGENTA 0xF81F
    #define YELLOW  0xFFE0
    #define WHITE   0xFFFF

    LGDP4535 tft; // Using the shield, all control and data lines are fixed

    #define YP A3  // must be an analog pin, use "An" notation!
    #define XM A2  // must be an analog pin, use "An" notation!
    #define YM 9   // can be a digital pin
    #define XP 8   // can be a digital pin

    // You need to calibrate to fit your LCD
    #define TS_MINX 930
    #define TS_MINY 903
    #define TS_MAXX 142
    #define TS_MAXY 117

    #define PENRADIUS 3
    #define MINPRESSURE 10
    #define MAXPRESSURE 1000

    int matrix[2][3]; // Initial Declaration
    int array[3]

    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

    // array = start with 1 but the variable read start with 0
    String ButtonAction[9]={"a", "b", "c", "d", "e", "f", "g", "h", "i"};
    boolean ActiveMenu=true;

    void setup(void) {
       Serial.begin(9600);
       tft.reset();
       tft.begin();
       ts.InitVariable(3, 240, 320, TS_MINX, TS_MAXX, TS_MINY, TS_MAXY, MINPRESSURE, MAXPRESSURE);
       tft.fillScreen(BLACK);
       DrawIt(CYAN, "draw");
       DrawIt(BLACK, "text");
    }

    void loop() {//SOME OTHER STUFF}

    unsigned long DrawIt(uint16_t color, String CurrentAction) {

      int timedcycle=0;

      if (CurrentAction == "text") {
         int matrix[2][3]={{25,150,265},{45,100,155}};
         int array[3]={3,3,3};

         tft.setRotation(3);
         tft.setTextColor(BLACK);
         tft.setTextSize(1);

         Serial.println("Text Columns");
      }

      else if (CurrentAction == "draw") {
        int matrix[2][3]={{260,140,20},{40,150,95}};
        int array[3]={3,3,3};
      }

      Serial.println(CurrentAction);

      for(int j=0; j<3; j++) {
         for(int i=0; i<array[j]; i++) {

           if (CurrentAction == "draw") {

             if (timedcycle == 7) {
               tft.fillCircle(100, 160, 15, WHITE);
             }
             else {
               tft.fillRect(matrix[1][j], matrix[0][i], 20,40, color);
             }

           }
           else if (CurrentAction == "text") {
             if (timedcycle == 4) {
               true;
               //tft.fillCircle(100, 160, 15, WHITE);
             }
             else {
               tft.setCursor(matrix[0][j], matrix[1][i]);
               tft.println(ButtonAction[timedcycle]);
             }

           }
         timedcycle++;
         }
      }
    }

So as you can see I'm trying to draw some things in a TFT Touch Screen. Everything seems to be working but no matter what I do I can't change the array value.

If I initialize the array variable with a predetermined value it won't change even if the statement is called correctly. I can see that it runs over serial but the array still doesn't change.

I suppose there's something wrong but I can't pinpoint what it is! Thanks in advance!

body:
It's because you are defining a *new* array every time, not modifying the existing one.

    int matrix[2][3]={{25,150,265},{45,100,155}};

That line doesn't assign new values to the existing `matrix` array, instead it creates a new array called `matrix` which only exists within the current scope - that is, within the `{...}` defined by the `if` that it is within.

Instead you either need to assign values directly to the existing matrix array on a slice-by-slice basis (you cannot use `{...}` to assign them in bulk):

    matrix[0][0] = 25;
    matrix[0][1] = 150;
    ... etc ...

Alternatively, since the values are static, you can pre-define the different matrices in the global scope and then switch between them.  This can be done with the right kind of pointer. For instance:

    int textMatrix[2][3] = {{260,140,20},{40,150,95}};
    int (*matrix)[3];

    void whateverTheFunctionIs() {
        if (whatever...) {
            matrix = textMatrix;
        }
    }

In that example `matrix` is a pointer to an array of pointers, which is basically what a 2D array is internally.  It starts off by not being assigned to anything at all - it's just "dangling in the breeze".  When the `if` in your function is triggered the address that the `matrix` pointer points to is changed to that of the `textMatrix` 2D array, so any access to `matrix[x][y]` will be identical to accesses to `textMatrix[x][y]`.


sender: user

message:
Arduino does not work

When I try to upload a sketch to my Arduino Uno R3 then sometimes I get the following issue:

At the beginning the RX LED flashes three times and then I get errors:

        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd1
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd1

Sometimes I get this:

        avrdude: ser_open(): can't open device "\\.\COM3": Odmowa dostępu.

And sometimes Windows does not see the Arduino.

At this site https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board I read that to check the programmer I must to connect RX with TX and GND with RESET pins and then plug Arduino to my computer, open Serial Monitor and write anything and if you receive the same characters from the Arduino, then the programmer and USB cable are OK. It worked for me.

And I have got one more info. When I plug Arduino with USB to my laptop the L led lights. When I press Reset on Arduino nothing happens, it still lights.

I recently bought a new USB cable, and it worked one day and then I could not upload sketches again. I uninstalled and installed drivers, but nothing changed.

This is a short video with my Arduino https://drive.google.com/file/d/0ByeWvrEgy2gRbWdHQ3d5RWU3Mmc/view?usp=sharing

[![Photo of Uno][1]][1]

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

---

I will buy USBasp programator is it a good idea?

sender: assistant

body:
It's normal that the `L-LED` is steady `on` after the USB connection is established. However, after pressing and releasing `Reset` it should flicker for a second, then go back to `on` again.

Check https://www.arduino.cc/en/Guide/Troubleshooting#toc1 for reasons why you can't upload.

On http://www.arduino.org/products/boards/4-arduino-boards/arduino-uno I've found:

> The Arduino Uno has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.

I haven't found out so far, how to read the current values of the fuses.


body:
1. Serial could be flooded if you were spamming it in ur last program you uploaded.
2. Ur arduino is broken
3. Try reflashing ur bootloader which is a common problem when you see data sync errors.


body:
> I will buy USBasp programator is it a good idea?

Yes, buy the USBasp programmer, reflash the bootloader with it, and try uploading code again. A corrupted bootloader very well may be the problem.


message:
Arduino loading variables from an SD card

Hello I have made a small game using and Arduino Uno and a Nokia 5110 screen. I use bitmaps to draw the images onto the screen. The problem is that bitmaps take up a lot of space and I can only use up to three bitmaps before running out of space. Is it possible to use an SD card to store the bitmaps on and have a method in the Arduino code to load a bitmap at a certain time, like when a button is pushed?

body:
Yes, it is possible, but is it practical?

There's basically two ways of doing it:

1. Load the entire bitmap into RAM for displaying multiple times
2. Display the bitmap direct from the SD card.

As the Uno only has 2KiB of RAM that rather limits the size of bitmap that can be loaded into it. As you currently can have 3 bitmaps in flash (max 32KiB) I will assume they are considerably bigger than 2KiB each, so loading them into RAM is not really going to be doable on the Uno.

So the second option - drawing it direct from the SD card - is really the only practical way. The problem with that is reading from the SD card is considerably slower than reading from the internal Flash.  That means that your screen updates could be really slow, which would seriously impact the playability of your game.

All that happens when you draw a bitmap normally is that a loop iterates through the data and interprets each bit of each byte as a pixel being on or off and sets the relevant pixel to be on or off on the screen.  Instead of reading data from flash you just read bytes from the SD card and interpret them in exactly the same way.  If you take a look at the bitmap drawing routine in your LCD library you will see how simple it is - replacing the Flash access with SD card reading should be a simple enough matter to implement in your own copy of the routine.

A much better option would be to use a more powerful Arduino - one that has considerably more flash, such as the Mega2560.


body:
Typically a bitmap for the Nokia 5110 (PCD8544) requires 504 bytes of memory (48*84/8). A bitmap as a initiated global variable will be stored in program memory, transfered to data memory on startup and then to the device (when drawn). Three bitmaps will use up 1.5 Kbyte. This is the limit for the Arduino Uno as an additional bitmap will require all data memory.

The first trick that can be used is to define the bitmaps in [program memory][1] with the attribute PROGMEM and when needed [transfer][2] to a buffer (504 byte) in data memory (and then to the device).

    void *  memcpy_P (void *, const void *, size_t)

The second trick is to transfer the bitmap directly from the program memory to the device. This may be supported by the library. If not the bitmap draw function will need to be updated to explicitly read program memory.

The upper limit for the bitmaps is now the size of the program memory (30 Kbyte, 60 bitmaps).

Cheers!

  [1]: http://www.nongnu.org/avr-libc/user-manual/pgmspace.html
  [2]: http://www.nongnu.org/avr-libc/user-manual/pgmspace_8h.html


message:
Arduino and reading from multiple USB connections

I'm sending up a high-altitude balloon with an onboard [Mighty Ohm Geiger Counter][1] and some other sensors, all of which will be managed by an R Pi B+. I'll collect and store the data with the R Pi; all of that's fine.

In order to track and recover it, I'm using the HABDuino shield on an Arduino. It uses the APRS system and sends back short messages, giving the altitude, internal temp, my callsign, and coordinates. I'd like to add the Geiger counter's data to that, but I'll need to get it from the R Pi.

Currently, I'm using an FTDI Friend to connect the Gieger counter to the R Pi, and getting the data from the serial port. I see [here][4] that I can connect the Arduino and Pi vai USB, but... since there's already a USB connection to the Gieger counter, will there be a conflict? Is that something that I can work around?

Thanks for the help!

  [1]: https://mightyohm.com/blog/products/geiger-counter/
  [4]: http://www.seeedstudio.com/recipe/166-basic-pi-lt-gt-arduino-communication-over-usb.html

body:
The FTDI should be showing up as `/dev/ttyUSB0` on the Pi.

If you connect an Arduino as well it will show up as `/dev/ttyACM0`.

If you don't have enough USB sockets then just add a USB hub.


message:
Why can I power an SD card reader from a digital pin?

I'm trying to understand the power requirements of an SD card. I have a cheap breakout board from eBay that includes built-in level shifters, so I can plug it in directly to my Arduino. I provide power from one of the digital pins, and it works. This doesn't make sense to me, as I thought an SD card reader should draw upwards of 50-100 mA, well over the capacity of an individual digital pin on the Arduino. However, at least one [SD card manufacturer][1] does this as well, so I'm not making this up.

I have checked, and the data is written no problem. I have connected an ammeter between the Arduino and the SD reader, and it never jumps above 3 mA? The only problem I have is when I switch from using the USB cable (connected to my computer) for power to a battery pack, the SD card starts acting erratically. Which makes sense, if it's not getting enough current.

What I'm wondering is why it *ever* works when connected to a digital output pin? Clearly I'm missing something important.

Edit: The reason why I thought they required a lot of current: I've seen comments like this on a number of [tutorials][2]:

> One is that they are strictly 3.3V devices and the power draw when writing to the card can be fairly high, up to 100mA (or more)!

Edit2: @dlu answer lead me to investigate the voltage I was sending to the SD card reader, which turns out to have been the problem. I was supplying the Vin pin with 5.2V, which was regulated down to 4V, presumably too low for the 5V-3.3V step-down at the SD card. Moving the battery power to the 5V pin corrected this. This also introduces some new risk, as the board is now [receiving unregulated power][3]. But that is another problem.

Edit3: And finally, answering my original question: I found a note on the [Adafruit product pag][4]e for a similar breakout that indicates:

> Onboard 5v->3v regulator provides 150mA for power-hungry cards

So despite only drawing 3mA of current from the Arduino pin, the actual SD card is supplied with > 100mA from the regulator.

  [1]: https://www.cooking-hacks.com/documentation/tutorials/arduino-micro-sd
  [2]: https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/look-out
  [3]: https://arduino.stackexchange.com/questions/4458/what-are-the-5v-and-vin-pins-for
  [4]: https://www.adafruit.com/product/254

body:
It seems that you've verified that the power requirements are within the range of a digital pin. Is there a reason why you thought they would be higher?

So, it sounds like the real question is "why does the SD card work with USB power, but not with battery power?" The first thing that occurs to me is that the battery is not providing sufficient voltage. What kind of battery are you using and where do you connect it to the Arduino?

Almost any battery that you use will be able to provide sufficient current for a 3 mA load, but the voltage may not be adequate – especially if you are running a marginal battery (voltage wise) through the onboard regulator.


body:
I just tested a SD card in an adapter (with level shifters). Without any activity the SD card is only drawing around 0.5 mA. So that is in the capability of an output pin.

Doing a directory list appears to use a maximum of 7 mA, so that is OK.

Writing a file used a maximum of **54.3 mA**, which is exceeding the absolute maximum ratings for an output pin (40 mA - recommended only 20 mA for continuous current).

Now you may say that "it works" but the question is: for how long? Exceeding absolute maximum ratings is a path to damaging your processor.

If you want to turn the SD card on and off from time to time, to reduce power, I suggest you arrange to switch the 5V line (and not use a digital output). For example from this [page about a low-power temperature sensor](http://www.gammon.com.au/forum/?id=12106) I have this schematic:

[![Power switching MOSFET][1]][1]

The MOSFET there switches a 5V line on and off under program control.

That particular design includes a SD card, and that particular gadget has been working for a couple of years now.

Photo of hardware:

[![Temperature and humidity sensor][2]][2]

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


message:
Correct solution for "multiple definition of" compile error

I'm in the process of trying to take [this demo sketch][1] and extract the necessary bits into a modular library that can be included in other sketches.

[Here's where I'm at so far][2].

Here's [the test sketch][3] that I'm including it in.

However, when I try to compile it right now, I'm getting...

    libraries/Adafruit_CC3000_Dynamodb/sha256.cpp.o: In function `Sha256Class::init()':
    /home/me/sketchbook/libraries/Adafruit_CC3000_Dynamodb/sha256.cpp:33: multiple definition of `Sha256Class::init()'
    sketch/sha256.cpp.o:sketch/sha256.cpp:33: first defined here

I've been programming for years in other languages, but I'm not all that experienced in C. I'm sure I'm doing something completely stupid, but I can't figure out what it is.

I'm also aware that this code still needs a lot of cleanup work in general. Right now I'm just trying to work toward a basic MVP that works so that I start gradually cleaning things up and making it more OOP one step at a time.

  [1]: https://github.com/tdicola/CloudThermometer/tree/master/CloudThermometer
  [2]: https://github.com/maketronica/Adafruit_CC3000_Dynamodb/tree/2ed5c6c8e251be4c0993ed0a1d68a85abe71d62d
  [3]: https://github.com/maketronica/cc3000test/blob/d22022cb76c2dbc92547a1ce7bca0fe97e106a6b/cc3000test.ino

body:
You have an old copy of the sha256 files lingering in the build folder. These will have been output at some point in the past and never been cleaned up since they have been deleted from the IDE.

It is probably a bug in the IDE that doesn't remove the old files.

Restarting the IDE will cure the problem and allow you to compile.


message:
Few questions related to programming microcontrollers

I'm learning "Arduino" (I don't have previous knowledge of microcontrollers). I have few questions:

1. What is the difference between programming a microcontroller in C and programming in "Arduino?"

2. Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?

3. I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differences between various microcontrollers which can be used with this board?

4. If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

That's it :)

body:
1. The Arduino IDE uses C++ primarily, which it preprocesses in order to make compilable. But you can still for the most part use C in the Arduino IDE and it will just work as normal; there's nothing requiring you to use C++ or the Arduino libraries (or even the Arduino IDE) for most tasks.

2. Not touching this one. And in the end it doesn't matter terribly since they're very close.

3. Any of the ATmegaXX8 or ATmega8 chips will fit the socket. Note that they will require separate cores if you're using the IDE. And you can use any chip without the board in the IDE as long as you can find a core for it.

4. Not if you use a traditional compiled language to program it. If you use a VM then you conceivably could, but you'd have the source on your system regardless.


body:
1. Nothing really.  The Arduino language is C++, a super-set of C. It contains a library of routines which are automatically included and linked, as well as a small amount of pre-processing to hide some of the pitfalls of C (e.g., automatically adding function prototypes for all functions to the top of your program so function ordering isn't something you now need to think about). Other than that, it is just C++, which is C with bells.
2. If you learn the Arduino language you are learning C. If you learn C first then it gives you a good grounding in how to program the Arduino. Either way, by the time you have written your first Arduino program, you will be programming in C.
3. There are a number of chips by Atmel that will work. You need, besides the "core" that Ignacio mentions, a board definition which defines what pins do what and what chip is in use. You also need a bootloader for that specific chip and some way to install that bootloader into the chip. There are tutorials on how to do that for commonly used chips - more uncommon ones may not have a bootloader readily available.
4. When you program for the Arduino you are compiling the software. That is turning the source code first into object code and then linking the object code into an executable format - almost exactly the same as a .EXE on Windows. There is nothing you can do to "undo" that, only disassemble the raw instructions into assembly language and try to interpret what it is doing, which with assembly is a bit of a black art since it can be somewhat cryptic.


body:
>    What is difference between programming microcontroller in C and programming in Arduino?

The difference is that the Arduino core includes a set of functions and classes (C++) to make Arduino boards easier to program.

>    Is it good idea for beginners to start programming microcontrollers in Arduino and then start learning programming in C?

The whole idea with Arduino is to make it much easier to start embedded programming in C and/or C++.

>    I have Arduino Uno board Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differenes between various microcontrollers which are used with this board?

None. This is the controller for that board (though there are "smaller" versions).

>    If microcontroller is already programmed, can we download program from it to PC and edit it in Arduino IDE? Or it is like .exe on PC, once compiled we can't get source, only we can do is Reverse Eng.?

This you will have to explain better. Sounds like something bad and you should avoid that (or at least do not ask people to help you do a bad thing).


body:
> What is the difference between programming a microcontroller in C and programming in "Arduino?"

The default language is C++, but you can program in C. Thus the difference is "not much".

>  Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?

Ah, if you program the Arduino you will be learning C. So "goodness" doesn't really enter into it.

> I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board?

You could conceivably remove the chip and replace it with an Atmega168P. I'm not sure why you would want to.

> What are differences between various microcontrollers which can be used with this board?

RAM, program memory (flash) size, and EEPROM size.

> If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

No. Like a PC, you can't get the source back. The compiler is a good, highly optimized one. The generated code won't look like the source.


message:
Update code over Ethernet?

I've got an Arduino faithfully monitoring our sewer lift pump. It talks to the world over Ethernet (with PoE). I'm wondering if there is any way to load new code over the Ethernet as well. Any ideas if this could be done?

I imagine that using the boot loader might be out of the question, but perhaps it would be possible to upload a new system image – perhaps onto an SD card – and then use a modified boot loader to discover the new image and copy it into place.

body: A bootloader to network-boot might be too large to leave enough code space for your application. Your second suggestion sounds more workable - to collect & verify the entire new image in secondary storage first, then call a storage-to-flash boot loader. You really don't want to start loading an image that then suffers damage in transit, or to have the link go down mid-download. The likely only way out of that is a site-visit. Saving first lets you confirm the integrity of the new image before you start over-writing any of the old one.


message:
How to upload Arduino sketches to Atmel chips

I am new in this Arduino coding world and I was trying to make a project. I normally used Arduino Unos all the time, but I was facing a problem and that is that the Arduino Uno has only 13 digital pins and 6 analog pins, and some of my friends advise me to use an Arduino Mega, but that costs too much, some to my friends also tell me that I could use only a Atmel chip, which will save money.

But the problem is that I can not burn these chips without a burner. I see online that Arduino Uno has Arduino ISP options also that will allow you to bootload or upload Arduino sketches to those kind of chips, but I have been trying for over 3 months and I cannot figure out how to do that

At present I am working with the ATmega8 chip.

This is my problem:

[![avrdude error - 1][1]][1]

Using stk500v1 but the problem is not resolved

[![avrdude error - 2][2]][2]

  [1]: https://i.stack.imgur.com/6v1rt.jpg
  [2]: https://i.stack.imgur.com/qjjbb.jpg

body:
First thing you need to do in this situation is to crank up the verbosity level on the invocation of `avrdude`. You do this by adding one or more `-v` flags to the command line. With `-v -v -v -v`, you get maximum verbosity.

From your two logs, it appears that the initial handshake with the microcontroller was successful (which would indicate that your connections were good), but then the signature reading turns out quite badly. This is a rather unusual combination which makes me wonder whether you may have misidentified what microcontroller you have.


message:
Can't send HTTP request using ESP8266 and Arduino Uno

I have an Arduino Uno and for Wifi an ESP8266.

My ESP8266 Firmware is

    AT+GMR

    AT version:0.40.0.0(Aug  8 2015 14:45:58)
    SDK version:1.3.0
    Ai-Thinker Technology Co.,Ltd.
    Build:1.3.0.2 Sep 11 2015 11:48:04

************

    baund = 115200,
     Both NL & CR

Server -- www.linysoft.com

The URL I want to send is either: `http://www.linysoft.com/arduino/?light=off` OR `http://www.linysoft.com/arduino/?light=on`.

Depending on to the link I send the result should be either ==> on or ==> off on the page `http://www.linysoft.com/arduino/light.json`.

Now I want to send an HTTP request (Weblink - `http://www.linysoft.com/arduino/?light=on`) so it can write according to that link "on" in the `light.json` page.

The AT command I am sending (my wifi module is connected to my wifi automatically):

    WIFI CONNECTED
    WIFI GOT IP

    AT+CWMODE=1

    OK

    AT+CIPMUX=1

    OK

    AT+CIPSTART=0,"TCP","www.linysoft.com",80

    0,CONNECT

    OK

    AT+CIPSEND=0,200

    OK
    >

Here I am getting a problem after this > I can't send `**GET /arduino/?light=on**`. I also tried `GET /arduino/?light=on HTTP/1.0\r\n`.

After putting this line in the textbox, I press the Enter button or Send Button, but nothing happens.

It is stuck here > for some time. And then it shows me:

    OK
    > 0,CLOSED

Pin Connection

    ARDUINO UNO        ESP8266
    RX  -------------->  TX
    TX  --------------> RX
    VCC--------------> 3.3
    CH_PD ----------> 3.3
    GND -------------> GND

body:
The domain is missing. Try this instead:

    GET http://www.linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n

Cheers!

Ref. http://contractorwolf.com/esp8266-wifi-arduino-micro/


body:
linysoft.com is a virtual host. Just try going to http://100.42.56.28/ and see that the connection is reset.

So after the `GET /arduino/?light=on`, you have to also send `Host: www.linysoft.com` (on the next line).


body:
Just found out a POST wouldn't work. Try this GET request to turn on the light.

        GET /arduino/?light=on HTTP/1.1\r\nHost: www.linysoft.com\r\n\r\n

Then you can get the status of the LED by GETting light.json like this:

        GET /arduino/light.json HTTP/1.1\r\nHost: www.linysoft.com\r\n\r\n


body:
I was having same problem and this one solved the problem that after you get a '>'
sign then write

GET http://linysoft.com/arduino?light=on HTTP/1.0\r\n\r\n(or if you are directly writing this on serial monitor then press enter key twice and then wait for somemoment like 2-3 sec in this case dont put \r\n\r\n)

If this didnt worked then try
GET http://linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n

But in this I guess you need to specify arduino.php or arduino.html whichever type you have
and too you have to take care the cipsend should be the byte no of get request excluding \r\n\r\n and add 4 to it because we are too sending \r\n\r\n these are 4 character

I hope this will surely work for you


message:
Sending number as byte through serial

I'm trying to send data from an Arduino to an Android device.

I saw an online guide for that which provided this code:

<!-- language: c -->

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

    void loop()
    {
      byte msg[64];
      int len = Serial.available();
      if (len > 0)
      {
        len = Serial.readBytes((char*)msg, sizeof(msg)); // readBytes seems to need a char* not a byte*
        Serial.write(msg, len);
      }
    }

I tried that example and it is working perfectly!

But when I put `Serial.write("3");`
in the setup loop after `Serial.begin(115200);`
it appears as question mark on my Android device,
I guess that I'm not sending it as a byte,
I searched online but without any luck.

body:
Start by changing it to `Serial.write("3", 1);`

Does that help, you're missing the second parameter to the Serial.write call, which is the number of characters (bytes) to write.


body:
I think this is a timing issue. It is fairly normal for a garbage byte or two to be received shortly after doing a `Serial.begin()` because the transition of "not defined" (or high impedance) output to Serial (which is normally all 1-bits) can cause the receiver to think it got a start bit, and then misinterpret what follows.

Try adding a short delay after `Serial.begin`. You could also try a pull-up resistor on the serial Tx line to ensure it is high prior to `Serial.begin` being called.

Your use of `Serial.available` effectively builds in a delay.


message:
NRF24L01 Connection Not Working

I have an ATTiny85 connected to an NRF24L01+ module using this wiring diagram: [diagram][1]. The ATTiny85 periodically goes in and out of sleep to send some value to a receiver, an Arduino Uno. If the ATTiny is running off the Arduino power supply (3.3v), everything works correctly. When I run the ATTiny off of a separate CR2032 coin cell that delivers around 3v, the Arduino never receives any data. I have a status LED hooked up to the ATTiny to ensure that the ATTiny is waking correctly, which it is. Here's the code for both:

**EDIT**:
Connecting it to an external 3.3v not from the Uno makes everything work - why wouldn't the coin cell's voltage work? I think everything is rated below 2.8v, the CR2032 minimum.

**ATTiny Code**

<!-- language: c -->

    #include <avr/sleep.h>
    #include <avr/interrupt.h>

    // Routines to set and claer bits (used in the sleep code)
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    #define CE_PIN 3
    #define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN

    #include "RF24.h"

    RF24 radio(CE_PIN, CSN_PIN);

    byte address[11] = "SimpleNode";
    unsigned long payload = 0;

    void setup() {
      radio.begin(); // Start up the radio
      radio.setAutoAck(1); // Ensure autoACK is enabled
      radio.setRetries(15,15); // Max delay between retries & number of retries
      radio.openWritingPipe(address); // Write to device address 'SimpleNode'
      pinMode(4, OUTPUT);
      digitalWrite(4, HIGH);
      delay(500);
      digitalWrite(4, LOW);
      delay(500);
      digitalWrite(4, HIGH);
      delay(500);
      digitalWrite(4, LOW);
      delay(500);
      digitalWrite(4, HIGH);
      delay(500);
      digitalWrite(4, LOW);
      delay(1000);
      setup_watchdog(6);
    }

    volatile int watchdog_counter = 0;

    ISR(WDT_vect) {
      watchdog_counter++;
    }

    void loop()
    {
      sleep_mode(); //Go to sleep!

      if(watchdog_counter >= 5)
      {
        digitalWrite(4, HIGH);
        watchdog_counter = 0;
        payload = 123456;
        radio.write( &payload, sizeof(unsigned long) ); //Send data to 'Receiver' ever second
        delay(1000);
        digitalWrite(4, LOW);
      }
    }

    //Sleep ATTiny85

    void system_sleep() {

      cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
      sleep_enable();

      sleep_mode();                        // System actually sleeps here

      sleep_disable();                     // System continues execution here when watchdog timed out

      sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON

    }

    // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
    // 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
    void setup_watchdog(int ii) {

      byte bb;
      int ww;
      if (ii > 9 ) ii=9;
      bb=ii & 7;
      if (ii > 7) bb|= (1<<5);
      bb|= (1<<WDCE);
      ww=bb;

      MCUSR &= ~(1<<WDRF);
      // start timed sequence
      WDTCR |= (1<<WDCE) | (1<<WDE);
      // set new watchdog timeout value
      WDTCR = bb;
      WDTCR |= _BV(WDIE);
    }

**Receiver Code**

<!-- language: c -->

    #define CE_PIN 7
    #define CSN_PIN 8

    #include <SPI.h>
    #include "RF24.h"

    RF24 radio(CE_PIN, CSN_PIN);

    byte address[11] = "SimpleNode";
    unsigned long payload = 0;

    void setup() {
      while (!Serial);
      Serial.begin(115200);
      radio.begin(); // Start up the radio
      radio.setAutoAck(1); // Ensure autoACK is enabled
      radio.setRetries(15,15); // Max delay between retries & number of retries
      radio.openReadingPipe(1, address); // Write to device address 'SimpleNode'
      radio.startListening();
      Serial.println("Did Setup");

    }

    void loop(void){
      if (radio.available()) {

        radio.read( &payload, sizeof(unsigned long) );
        if(payload != 0){
            Serial.print("Got Payload ");
            Serial.println(payload);
        }
      }
    }

Is the problem here that the ATTiny and Uno need to be turned on at the same time to establish a connection, or is it something to do with the battery, or something else entirely? Any help would be appreciated.

  [1]: https://www.hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2

body:
I was just researching the exact question and I have some bad news.

The ORIGINAL nrf24l01+ alone use around 10-12 ma in transmitting, but unoriginal might even draw more. (https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf)

Nevertheless a standard CR2032 battery is simply not made to supply more than a few milliamps at the best, leaving your nrf24L01+ lacking enough current.

There is something called shockburst which can lower your consumption considerably at the cost of range - but if it will succeed in transmitting with one CR2032 I'm not sure about.

Edit:
If you add a capacitor you need to cover at least a 10ma drain for around 15ms (turn on - send - turn of immediately), that will require a minimum of a 200µF capacitor at 3V to be able to deliver the current while keeping above 2.0v.


message:
Pinout for Leonardo USB

According to the [docs][1], the Arduino Leonardo uses digital pins 0 and 1 for the [USB D- and D+][2] lines. However, which is which? e.g. is D0=D+ or is D1=D+?

To save space in a very tight project, I want to wire USB directly to these pins instead of using the USB plug, however, I can't find any resource that explains which pin goes to which USB line.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo
  [2]: https://en.wikipedia.org/wiki/USB

body:
The USB does not go to pins 0 and 1.  The UART goes to pins 0 and 1 - that is a totally different interface.

The USB is connected to dedicated USB pins on the chip.  If you look at the [Leonardo schematic](https://www.arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf) you can see it is pins 3 and 4 on the chip. Note that that is not pins D3 and D4 on the board, but the third and fourth pins anti-clockwise from the "pin 1" dot on the main chip.


body: As shown in the ATmega32U4 datasheet, D- and D+ connect to pins 3 and 4 respectively ***of the MCU***. But you don't want to wire directly to the chip unless you know what you are doing since the chip does not include the USB termination resistors. Follow the schematics given in the datasheet when connecting to the USB pins of the MCU.


message:
Do I need a lot of Arduinos?

I would like to make a smart home using Arduino. My system must be wireless. I want to control power outlets and lamps and I want to be able to turn off and on power outlets and lamps wirelessly, using my android app, using nRF24L01.

Do I need an Arduino for each power outlet and lamp? Do I need to put an Arduino, nRF24L01 and relay inside each power outlet and lamp?

body:
One arduino can control multiple relays. Beyond that, how many you need will depend on the details of your project.

Once you have a working example, you can build it using less expensive alternatives than regular Arduino boards.


body:
You might also consider using ESP8266 + relay combinations, instead of Pro Mini + nRF24L01 + relay sets.  An Arduino IDE setup is available to support C code on ESP8266 systems ([1](http://l0l.org.uk/2014/12/esp8266-modules-hardware-guide-gotta-catch-em-all/),[2](http://makezine.com/2015/04/01/esp8266-5-microcontroller-wi-fi-now-arduino-compatible/),[3](http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module)).

Note:  As a consequence of its higher clock speed and larger RAM size (80 MHz or 160 MHz clock, and 80 KB DRAM, vs Mini's 16 MHz clock and 2 KB SRAM) a typical ESP8266 board uses more power than a Pro Mini + nRF24L01 does.  According to [nrqm.ca/nrf24l01](http://nrqm.ca/nrf24l01/hardware/), the nRF24L01 draws around 11 or 12 mA when sending or receiving, and  22 μA in low-power standby mode.  According to [wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module](http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module#Electronic_Characteristics), an ESP8266 draws ~ 60 mA receiving and 135–215 mA sending.  (That current range covers a power output range of 5.5 dBm.  It probably supports a much bigger communication area than nRF24L01 does.)  Of course, if all your installations have mains power available, the power requirements might not matter much to you.  Note, ESP8266 boards typically run on 3.3 V power instead of 5 V power.

As far as cost goes, at the moment Pro Mini clones cost about $2.15 each.  nRF24L01's run about $0.90.  ESP8266 modules are $2–$3 depending on model and level of module ([1](https://www.itead.cc/esp8266-serial-wifi-module.html),[2](http://www.ebay.com/itm/ESP8266-Remote-Serial-Port-WIFI-Transceiver-Wireless-Module-Esp-07-AP-STA-OT8G-/371241185691?pt=LH_DefaultDomain_0&hash=item566fb2f19b)).  You might save a few dollars on your whole system using ESP8266's, but the smaller-sized electronics they provide probably is more important.


message:
ESP8266 (connected to Arduino) only works when plugged into USB power

The Wi-Fi connects when the Arduino is powered by my computer and a serial console is connected, but not if I plug into an outlet.

**UPDATE**

It seems this is a power issue. I am powering the esp8266 from the Redboard 3.3v line that is only rated for 150mA. I will be switching to the 5v line with a 1A regulator.

I also switched to 9600 baud for communicating with the esp8266, added retries around all of esp8266 commands, and added reconnect logic in case the esp8266 reboots. With the changes, it works okay even with the underpowered 150mA line.

It's still a mystery to me why it works so well when connected to my Macbook.

body:
It sounds like your power supply is inadequate to the task.

The ESP8266 is notoriously finicky about having a noise free power supply capable of delivering a lot of instantaneous power. If you are using a wallwart style supply it should promise at least 1A and more is better. Even though the actual use is more like 250 mA.


message:
I want to pour 500ml of Water in jar with Arduino water flow controller?

I want to pour 500ML of water with Arduino water flow controller with maximum accuracy.
How will I get the maximum accuracy with this sensor?
Could someone can give suggestion for accuracy or any other sensor that i can use?
[![enter image description here][1]][1]

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

body:
You haven't specified what level of accuracy you are aiming for so I have assumed 0.01ml.

What ever solution you go for you will also need an accurate temperature and pressure sensor, because these will affect the density of the water.
Each individual sensor you use has a degree of error associated with them.  You would nee to calibrate each sensor to establish what level of error each individual instance of a sensor has.

Weight would seem to be the best solution.  Surface tension could affect a flow metre or a contact sensor.  I have to be honest I don't see how an ultrasonic sensor could give you any degree of accuracy.  With a weight sensor you would need to establish the dry weight of the container then pour the liquid in until the desired volume was achieved.  A quick response to close the very end of the inlet pipe would be required to prevent un-necessary drips.

As to marking the container, are you using some computer controlled marking tool, because if you are just drawing on the side with a Sharpie you may as well use a measuring jug. :)

You should be able to get a weighing PCB, a pressure and temperature sensor off any of the usual electronic sites to suit you budget and the libraries will be on Git hub.


body:
The flow meter you specified, YF-S201 Hall Effect Water Flow Meter [(datasheet)](https://www.olimex.com/Products/Components/Sensors/SNS-FLOW201/resources/Water_flow_sensor_datasheet.pdf) measures the water flow rate, producing signal output frequency in range 16Hz (at 120L/H) to 90.2Hz (at 720L/H). Datasheet claims "error range +/- 10)". **Note that this only measures the rate of flow, it is not a valve and so does not control the flow.**

Problem with using a flow rate sensor to measure total quantity of water, is that you must constantly integrate the flow rate over time to get the total volume. Any errors in rate measurement or integration time, will accumulate; so this is generally not an accurate approach. **Cumulative errors are highly undesirable, because they are difficult to detect and compensate.** You have to not only measure the output frequency, but also carefully control the time between measurements, because you are integrating over time. This will be even more of a problem if you are printing out messages to the serial port.

If the water supply is well regulated and always provides a steady flow, then you will open the valve for a specific time interval. But if the supply pressure is not well regulated, then you may accumulate integration errors and dispensing will not always be accurate.

If you care about dispensing precisely 500mL of water, a more practical solution is to use a weigh scale (*load cell*). First, measure the *tare weight* of the empty container, then dispense (using a control loop) until net increase in weight is 500g. With this setup, the dispenser accuracy is determined by the load cell repeatability error (0.1% for a good quality load cell, a couple % for a fair quality load cell) and the measurement accuracy of the ADC (depends on resolution and reference voltage stability). You could try using the Arduino's on-chip ADC which is only 10 bits, or for best accuracy use a real 24-bit weigh scale ADC. The load sensor's *offset error* is set to zero by measuring the tare weight of the empty jug, so you only need to be concerned about *gain error* at 500mL and *repeatability* of the load sensor. **This approach does not have cumulative errors.**

You have not specified what kind of valve you will use to control the flow. If you use a *solenoid value*, the valve is only on-or-off, there may be some overshoot due to valve reaction time (10ms), so you will need to experiment and determine an "off threshold" before reaching 500g.

Since you have no way to compensate if the system overfills the jar, you will need to dampen the system response so that it slows down as it approaches the target level, without overfill. I'd therefore suggest using a *proportional valve* instead of a solenoid valve. Start with a fast flow rate when net weight <400g and then switch to a slower rate as the jar reaches its target weight.


body: Another option is to use a stepper motor and a Peristaltic Pump (or IV pump). You can use this to control the flow rate AND volume. For speed you need to make the motor run faster and for volume just run the stepper motor x times to get x volume. I do not know how precise it is. Good luck with what ever option you pick.


body: I suppose that you already found a solution. If you haven't, one inexpensive way for the Arduino to sense when the water reaches the desired level is to drill two thin parallel holes into the container (using a wire gauge drill bit, provided you're not using glass or something difficult to drill) slightly below the "trigger point." Then, you can insert two thin strands of conductor so that they protrude a millimeter or less inside the container(consider something like graphite 0.5 mm pencil leads to prevent corrosion). You'll need to seal the holes using epoxy. If you make a voltage divider and put these two pencil leads in the place of the second resistor, you can measure the resistance change (using an Arduino analog input pin) when the pencil leads are "connected" by the water. Once you find the ADC value for the "water full" state of your connection, you can make the Arduino turn off the flow when this value is detected. You should place the pencil leads below the "trigger point" so that you can experiment with different delay periods between sensing the water and turning the flow off (to compensate for the water that remains in the pipe "downstream" the flow controller. I've used this approach successfully to measure flow rate, but I can't guarantee it would work in your application.


message:
Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V?

To control my robot, I need to generate negative and positive voltage in a single line, because the motor I try to control is an industrial one.

Do you have any suggestion for it? How can I produce a negative voltage using an Arduino board and simple electrical elements?

body:
Your question should read:

> How do I scale a 0 to 5 V signal to -10 V to +10 V?

First write the conversion formula:

    Vout = 4 * Vin - 10

Testing the formula gives the following:

 - Vin = 0.0 V ==> Vout = -10 V
 - Vin = 2.5 V ==> Vout = 0 V
 - Vin = 5.0 V ==> Vout = +10 V

You will need an op-amp circuit to create this function. In addition you will need a +12 and -12 V supply.

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

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

<!-- End schematic -->

How it works:

 - OA1 is an op-amp wired in an _inverting_ summing amplifier configuration. We'll address the inversion later but for now all the answers will be "upside-down". The gain is set by -R2/R1 = -40k/10k = -4. If we feed 1 V in from the ADC we will get -4 V out.
 - R3 provides a negative input. The gain will be set by -R2/R3 = -40k/48k = -5/6. Since it's connected to -12 it will contribute +10 V to the output.
 - The actual output will be the sum of the two: in our example, +10 - 4 = 6 V.
 - C1 and C2 provide noise filtering for the op-amp. Place them close to the chip.

Now, what to do about the inversion? We have three choices:

1. Fix it in the micro controller code. Set +5 V as maximum reverse speed / torque. Set 0 V as maximum forward speed / torque.
2. Fix it in the servo amplifier and tell it to reverse its command signal.
3. Fix it in the electronics. By adding another inverting op-amp we can turn the signal the right way up.

The TL082 opamp suggested has two op-amps in the one 8-pin package.

Ref: [Inverting Summing Amplifier](http://masteringelectronicsdesign.com/how-to-derive-the-transfer-function-of-the-inverting-summing-amplifier/).

<hr>

**Servo Enable**

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

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

<!-- End schematic -->

Delay the servo enable until the micro controller has initialised and all other functions are ready. See manual Section 3.2.3, page 73.

Note that this is a simplified relay drive schematic. You need a transistor drive and a snubbing / flyback diode around the relay so one of the small 5V relay boards would be a good solution as they are already built in. An opto-isolator would be simpler.

Ensure that safety circuits (guarding and e-stops) are correctly wired using safety-rated components (and not only, for example, the micro).


body:
"transistor" has walked you through what is necessary. Just an additional point of note: if you don't have a +/- power supply, you can easily generate the negative voltage using eg ICL7660 or even using a 555: https://www.ikalogic.com/555-based-voltage-inverter-schematic/

Just because I'm curious, could you add a link to the servo datasheet?


message:
Why does Ethernet.begin() require a MAC address when WiFi.begin() doesn't?

I am working on an Arduino application which is dependant on a certain library. This library uses the `Ethernet` class for network communications, but ideally, I would like it to be wireless (I have both an Ethernet and WiFi shield available for testing).

When working on replacing the [`Ethernet`](https://www.arduino.cc/en/Reference/Ethernet) functionality of the library with the corresponding [`WiFi`](https://www.arduino.cc/en/Reference/WiFi) functionality, I noticed that the [`Ethernet.begin()`](https://www.arduino.cc/en/Reference/EthernetBegin) function requires a MAC address while the [`WiFi.begin()`](https://www.arduino.cc/en/Reference/WiFiBegin) doesn't (it instead accepts SSID and password, among a couple of other things).

As both come shipped with a MAC address sticker on them, I couldn't really figure out why this is the case (and if I need to supply the MAC address found on the WiFi shield in some other fashion).

Why is this the case?

body:
The flip answer would be "because it doesn't need it…"

I think what is going on is that older Ethernet shields did not have a MAC address and it was necessary for the code to set one (and I would guess that on at least some of them you can still set the MAC address, overriding the one that is on the sticker).

WiFi cards, I would guess, are newer and the MAC address is always there, so there is no need to require you to assign it.


message:
How to clear of contents of string in Arduino?

Currently I convert the characters in `char received[20]` to string using `String randomString(received)` and I am able to display it using `Serial.println(randomString)`. After displaying the string, I would like to know the easiest way to clear out its contents.

body:
In C and C++ a null terminated array of characters **is** a string (although not a String). Many routines for reading input terminate the result with a null as does an assignment like"

    char foo[] = "This is a string.";

All you would need to do to "clear" this string is to assign a null to the first character. For example:

    foo[0] = '\0';


body:
First version with conversion from char[] to Arduino String class:

    char received[20];
    ...
    // Some code that assigns received
    ...
    String randomString(received);
    Serial.println(randomString);

    // Clear string
    randomString = "";

Second version without the Arduino String class:

    char received[20];
    ...
    // Some code that assigns received
    ...
    Serial.println(received);

    // Empty received buffer
    received[0] = 0;

And third version where the buffer is cleared:

    char received[20];
    ...
    // Some code that assigns received
    ...
    Serial.println(received);

    // Clear received buffer
    memset(received, 0, sizeof(received));

Cheers!


body:
Although an old question, I thought I would chime in. If I took the time to understand the question properly, I believe you wanted to clear the contents of the String and not the char array. This may help those who wanted to empty a string for other reasons.

```
String randomString(received);
Serial.println(randomString);
randomString.clear(); // This will clear the string
```
It should be noted that for outputing, there was no need to convert to string first if that was all that was required, because println will prefer a char array anyway.

Again String has a `.clear()` method for those who reached this page via web search.

Update:
It has been pointed out thanks to @VE7JRO in the comments, that the `clear` methods availablity is not universal. The ESP devices with Arduino compatibile core libraries do have it, as may others. But AVR devices such as the UNO do not. Which I have confirmed.

A revised version to suit all cases where the `.clear` method is unavailable.
```c++
String randomString(received);
Serial.println(randomString);
randomString = ""; // This will clear the string
```


message:
Can I set an Arduino pin as input and output?

When I used to program PICs, there was a way to set the pins to input and output, at the same time. Can this be done on the Arduino?
I see the [pinmode documentation][1], but nothing about being an IO port.

  [1]: https://www.arduino.cc/en/Reference/PinMode

body:
No there is no function that lets you set all the pins to either input or output at the same time, but it wouldn't take much to write one.

No, you can't set an Arduino's pin as bidirectional.  If you are running out of pins look at IO expanders or multiple Arduinos.

Hope that helps, if not please feel free to clarify what it is you would like to know and we'll try and help.


message:
Controlling an LED using a transistor (TL188)

I wanted to control an LED using a transistor (my first attempt at using a transistor). I connected a transistor (TL188) to pin 13 of an Arduino Uno accidentally and noticed something.

[![Enter image description here][1]][1]
*(The resistor I used was 150 ohms, and I forgot to change the resistor value in the diagram.)*

The program on the Arduino Uno was the basic `Blink` sketch. As per the program, the LED on the Arduino Uno was supposed to turn on for 1000 ms and turn off for 1000 ms. But when I connected the LED like the diagram below

**For the first 1000 ms delay:**

 - LED on pin 13 stayed **on**
 - LED connected using the transistor stayed **off**

**For the next 1000 ms delay:**

 - LED on pin 13 stayed **partially on (it was dim)**
 - LED with the transistor was **on**

I know that the connection that I made is completely wrong. Can someone explain me how and also why the LED on the Arduino Uno was dim?

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

body:
You should have a resistor of a few hundred ohms on the base connection of the transistor - that is, between base and pin 13.

A PNP transistor is somewhat harder to get to grips with than an NPN transistor.  Much of it does things backwards.

The operation you see seems to be completely correct when you understand how a PNP works.

With and NPN transistor a high voltage on the base turns it on and a low voltage turns it off. The opposite is true with a PNP transistor.

When you have a voltage close to or above the voltage at the emitter the transistor will be off.  That means, providing a HIGH to the base will turn it off.  A voltage on the base that is below the emitter voltage minus the threshold voltage of around 0.7V will turn the transistor on.  That means providing a LOW to the base will turn it on.

So that means that when the on-board LED is on the transistor is off, and so the LED on the transistor will be off.  When the LED on the board is off the transistor will be on, so the LED on the transistor will be on.

"But", you say, "the on-board LED doesn't turn off".  That is correct. It just gets dimmer.  That is, again, because of how the PNP transistor works.  Current (seen from the *conventional sense* - i.e., flowing from + to -) enters the emitter and is then split between the collector and base. The amount of current allowed to flow out of the base defines how much is allowed to flow out of the collector (in an NPN it's current into the base and collector that combine to flow out of the emitter, and the amount that is allowed to flow into the base defines how much is allowed to flow into the collector). So there will be some current flowing out of the base - which makes its way to ground both through the microcontroller's IO pin and also through the LED on board, making it glow slightly*.

----

*That is a little crudely put, but kind of illustrates what is going on.


body:
It really doesn't matter if you use a PNP or NPN transistor, they are just mirrors of one another. If you have some common anode displays then just start directly with the PNP's.

The flaw I see in your circuit is that you should always use 2 resistors to drive a LED (See schematic). R2 (as you already have) will limit the current to the LED; 220 Ohm you as illustrated is fine.

R1 is needed between the I/O pin and your transistor. This will limit the current through the I/O pin. For what you are attempting a resistor in the range 1K to 2K should do, even if you're switching a few LED's in parallel.
If you provide complete details of your setup we can always refine the calculations. One can then take into account the total currents from your displays, the amplification factor of the transistor (hfe) etc. [![enter image description here][1]][1]

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


message:
Strange problem. Arduino stops working after few hours. Opinions please

I am trying to setup an automated relay for my aquarium. The Arduino should switch off the pump every 3 hours for 20 minutes, and feed at particular times during the day. The code works fine for the first two on/off cycles. However after that the system stops responding.

I have tried many ways to solve the issue, I am led to believe that the issue could be a memory leak, which I have tried to fix that with watchdog timer reset, I have also tried resetting the Arduino but it doesn't work after the first reset.

I am still not sure what the problem could be, so any information would be appreciated.

I have included the code that I have stitched together using references from the web and a schematic of my circuit along with a picture of a tiny RTC module.

Schematic:

 ![][1]
Tiny RTC:

![][2]

My code is below, any advice would be appreciated.

    #include "Wire.h"
     #define DS1307_ADDRESS 0x68
     #define RELAY_PIN 2
     #define Feed_PIN 4
     #define led13 13

     void setup() {
       Wire.begin();
       Serial.begin(9600);
       pinMode(RELAY_PIN, OUTPUT);
       pinMode(Feed_PIN, OUTPUT);
       pinMode(led13, OUTPUT);
     }

     void loop() {
       printDate();
       // digitalWrite(led13, HIGH);
       //delay(500);
       //delay(500);
       //digitalWrite(led13, LOW);
       // byte zero = 0x00;
       ///Wire.write(zero);
     }

     byte bcdToDec(byte val)  {
       // Convert binary coded decimal to normal decimal numbers
       return ( (val / 16 * 10) + (val % 16) );
     }

     void printDate() {
       // Reset the register pointer
       Wire.beginTransmission(DS1307_ADDRESS);
       byte zero = 0x00;
       Wire.write(zero);
       Wire.endTransmission();
       Wire.requestFrom(DS1307_ADDRESS, 7);
       int second = bcdToDec(Wire.read());
       int minute = bcdToDec(Wire.read());
       int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
       int weekDay = bcdToDec(Wire.read()); //0-6 -> sun-sat
       int monthDay = bcdToDec(Wire.read());
       int month = bcdToDec(Wire.read());
       int year = bcdToDec(Wire.read());
       //print the date EG   3/1/11 23:59:59
       Serial.print(month);
       Serial.print("/");
       Serial.print(monthDay);
       Serial.print("/");
       Serial.print(year);
       Serial.print(" ");
       Serial.print(hour);
       Serial.print(":");
       Serial.print(minute);
       Serial.print(":");
       Serial.println(second);
       if ( (hour ==  9 && (minute >= 00 && minute <= 20)) ||
            (hour == 12 && (minute >= 20 && minute <= 40)) ||
            (hour == 15 && (minute >= 40 && minute <= 59)) ||
            (hour == 18 && (minute >= 00 && minute <= 20)) ||
            (hour == 20 && (minute >= 20 && minute <= 40)) ||
            (hour == 22 && (minute >= 40 && minute <= 59)) ||
            (hour ==  1 && (minute >= 00 && minute <= 20)) ||
            (hour ==  3 && (minute >= 20 && minute <= 40)) ||
            (hour ==  5 && (minute >= 40 && minute <= 59)))
       {
         Serial.print(month);
         Serial.print("/");
         Serial.print(monthDay);
         Serial.print("/");
         Serial.print(year);
         Serial.print(" ");
         Serial.print(hour);
         Serial.print(":");
         Serial.print(minute);
         Serial.print(":");
         Serial.println(second);
         Serial.print(':');
         Serial.print(':');
         Serial.println(", pump off!");

         digitalWrite(RELAY_PIN, HIGH);
       } else {
         digitalWrite(RELAY_PIN, LOW);
       }

       if ((hour ==  2 && minute == 43 && second >= 52) ||
           (hour == 10 && minute == 00 && second >= 52) ||
           (hour == 13 && minute == 00 && second >= 52) ||
           (hour == 16 && minute == 00 && second >= 52))
       {
         digitalWrite(Feed_PIN, HIGH);
         Serial.println("feeding fish.....");
       } else {
         digitalWrite(Feed_PIN, LOW);
       }
     }

  [2]: https://i.stack.imgur.com/xrGPd.jpg
[1]: https://i.stack.imgur.com/kgoou.jpg

body:
Your code seems fine, I cannot give a comment yet due to me not being a high enough ranked member, so i will try to phrase this as annswer instead.

Your arduino might be the problem, but I don't think it is likely as the clock is known to be troublesome, but as "transistor" suggested you should let it run on the serial for some time so that you can see if time is reported correctly.

I time is not working then I would like to direct your attention to this thread on the arduino forum, as this is apperently a very poor module. Several people have clocks that doesn't function properbly and there is many post adressing troubleshooting, but since this is supposed to be answer I have taken the top issues and put in below.

https://forum.arduino.cc/index.php?topic=177297.0

primarely they problems come from:

an unrechargeable **Cr**2032 battery is shipped, instead of a rechargeable **li**2032, this cause the charging Circuit on the board to act up.

Fix : replace to **li**2032 or remove charging circuitry - se link

ungrounded crystal - may or may not be a real issue

Fix: ground the crystal

Bad crystal:

Fix: replace crystal

Error in design - Resistor nr. 7 in place

Fix: remove resistor


body: Perhaps you can try `while (Wire.available() != 7);` before calling `Wire.read()` 7 times in succession. Also remove leading zeros in the integer literals of 0 in your IF conditions. And make `bcdToDec` return an `int` instead of a `byte`, in the unlikely case of any overflow issues.


body:
I know a very rough brute force idea, but I'm afraid you won't like it.

Here, how it goes: Use additional relay for powering arduino: While arduino is turned on, let the power be connected to NC contact and after each cycle, just turn this output to HIGH. How it works, you ask? Well, after a cycle, you will with logic 1 (HIGH) state cause to "unplug" the arduino power, which will lead to loosing power supply. However, the relay has a spring, that in case of loosing power, it goes back to NC, in which case, your arduino will be reset and working for another cycle.

That should 100% work, but as I said before: It's a horrible brute force idea :)


message:
No Battery Microcontroller Operation - (Motion, heat, induction etc)

I am using an ATtiny85 to sleep for a long period of time, collect some data, send it over radio, and go back to sleep, after disabling everything possible. The ATtiny is currently powered by a coin cell. I can get quite some time off that coin cell, but it's simply not enough, and the coin cell cannot be changed once the board is deployed. Peak current draw is around 10-15 mA.

My aim here is to find an alternative power source for my board. Some good news is that the boards are never more than one or two feet from a receiver, so rf-like power transmission may be possible. Some other options may be motion or heat (it's a wearable device). The amount of power could be pretty small, as I only need it at peak periods, so I could just charge up a supercapacitor for a while and drain it when power is needed after the Attiny wakes up for less than a second.

The ideal situation would be to have a means of power transmission or generation that provides enough current to continuously power the microcontroller without the need for sleep, but I recognize that this is probably not feasible. However, due to the limited range it might be. Another concern is radiation to the wearer.

If anyone has any experience in this kind of power transmission or generation or just any ideas I would love to hear it. Thanks!

body:
10mA is quite a lot for a coin cell. And of course the duration is really low.

As for wireless power transmission, I highly discourage you. Since you are using coin cell batteries I think that size is a must for you, and for wireless power you will need a really big antenna. If it is a wearable I think that the receiver is on the body too, and so much power is not a good thing.

In my opinion and according to my experience you have two possibilities:

1. use alkaline batteries (e.g. AAA). Use a step up driver to get 3.3V from 1.5V (since the current you need is low you can use simple charge pump regulators, so with a 10pin TSSOP integrate and three small capacitors you are done) and you will get a really long lasting circuit. Drawback: AAA batteries are a bit large, so probably you'll have to make a bigger receiver

2. use lithium batteries (usually I use LiPo). You will then be able to recharge the battery with any power supply (I usually use an IC which can charge LiPos with a 5V source - USB - and a couple of other components (two capacitors and a LED with its resistor).

Personally I struggled with coin cells for a long time before giving up and sticking with lipos forever.


body:
This question seems to be aligned to your other question about nrf24l01+ transceiver. The charge pump is a good idea, but if this is still for the nrf24l01+ project i would not recommend it because it would cause ripples in the supplied power and RF noise which is really not something you want together with the nrf24l01+.

if the unit is to be strapped on the wrist or ankles a concept like the one in a shake/faraday flashligt might be implemented, but that would be a diy custom job. and probably require size, even though they can fit a similiar contraption into a wristwatch.

But anyway I'm not sure if you are aware, but the nrf24l01+ has a function called enhanced shockburst which is designed for very low current consumption according to the datasheet it only requires 1% or 0.12ma at normal transmitting mode! this comes at the cost of transmitting power ofcourse but your receiver is only a few feet away so that is most likely not an issue.

https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf page 14

I'm pretty sure you already have optimised your current consumption, but one setting you might have missed is  the atTiny clockspeed which can be lowered to 1mHz instead of 8mHz this will lower the current to run the processor to 20 of the normal.

if these are not implemented already, then they might give you the needed battery life.


body:
I just helped a friend install a Fitbit "Zip" model. In the process of doing that I noticed it is powered by a CR2025 (3V lithium button) battery.

Their ads claim it runs "up to 6 months" on this battery. It communicates wirelessly (ie. Bluetooth) as well as having an LCD screen. It also takes measurements.

Thus, what you are trying to achieve sounds technically possible, as someone has done it.

---

> I can get a few weeks depending upon usage, and I need a few months.

So to solve your problem it would help to know what your existing current consumption is.

I have a project about an [ATtiny85 torch locator](http://www.gammon.com.au/forum/?id=12769). That does not do radio transmission but **does** flash an LED. I calculate the battery should last 3 years, and at this stage (almost a year after I made it) it is still working on the same battery.

You may get some ideas from that link.

I calculated (and confirmed by measurement) that in idle mode it uses 4.4 µA. You should be getting a similar figure during your sleep periods.


message:
One time execution of a variable incrementation

As part of a larger script intended for a very simple arduino "synthesizer" I am trying to increment the amount of cycles a melody will be played once a key is pressed (the key in turn passes a value to the variable selectMel). The problem I encounter is that the moment I call my function in the main void loop() function, I cannot control the incrementation of the variable ncycles, which is intended to be only increased once per key press. I tried to solve this by creating a global switchVar variable as an "on/off" switch but that did not do much to solve the issue at hand.

Any tips or help will be greatly appreciated!

PS: I have of course googled and tried the solutions posted on similar stackExchange posts but to no avail, sadly.

          void playMan (int ncycles, int mSpeed) {

            switch (selectMel) {
            case 1:
              if (ncycles > 0) {
                tone(12, NOTE_B7, mSpeed);
                delay(100);
                tone(12, NOTE_B5, mSpeed);
                delay(100);
                tone(12, NOTE_B3, mSpeed);
                delay(100);
                tone(12, NOTE_B1, mSpeed);
                delay(100);
                ncycles--;
                break;
              case 2:
                if (millis() % 100 == 0) {
                  if (switchVar == 1) {
                    ncycles += 5;
                    switchVar = 0;
                  }
                  Serial << ncycles << endl;
                }
                break;
              default:
                break;
              }
            }
          }

body:
See <http://www.gammon.com.au/switches>.

Basically you need to detect the transition between the switch not being pressed before, and **now** being pressed. This transition will occur once per press (possibly after you add debouncing). If you just test for the switch pressed naturally you will get multiple increments.

---

> Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ?

To clarify, you increment once on a transition, note when you did this (eg, by calling `millis()` ) and then ignore any further transitions for, say 10 ms.


message:
Using an Arduino as the processor for a computer-mouse-like speed detector

I'm looking at making a pretty cheap and easy odometer, eventually for an electric car or similar vehicle.

My idea is to implement a big computer mouse, and track the speed with that: a computer mouse takes photos of the surface it is on, and finds the difference between sequential images in both the X and Y directions.

What I am wanting to do is to attach a downwards-facing camera; something like [this][1], to the bottom of the vehicle, and use an Arduino Nano to do the image processing to achieve a result similar to a computer mouse.

I was wondering whether anyone knows of an libraries/documentation on anything similar, or if anyone has any pointers on reasons why this would not work, or ways it would work.

Thanks all.

  [1]: http://www.aliexpress.com/item/Guaranteed-New-1Pcs-Blue-OV7670-300KP-VGA-Camera-Module-for-Arduino-Free-Shipping/1377974232.html?spm=2114.01020208.3.2.Ku9fjM&ws_ab_test=searchweb201556_2,searchweb201644_2_10001_10002_10005_10006_10003_10004_62,searchweb201560_1,searchweb1451318400_6150

body:
Whooa, wait a minute. This sounds way too complicated, and my guess is that a Nano would be seriously underpowered.

If you really want to do all that work, you probably would need to step up your processing power. I suggest that you do some calculations on that, the number of pixels per second that should be compared.

Also factor in the time it takes to capture the image, the device you suggested is probably not fast enough. My guess is that by the time you can take next picture of the surface, you don't have any part of the image to compare with. According to [wikipedia][1], a modern mouse has a 18 by 18 pixel sensor, and we're not talking a lot of (surface) speed here.

But there's a simpler solution; mount a magnet to one of the wheels (or axle) and a reed switch so that it is actuated as the magnet sweeps by. Then use the Nano (or a Trinket, no need for power here) to count the pulses from the reed switch. Do your math; (circumference of wheel) * (pulses per time unit). Convert to suitable format.

Voila; speed! :-)

This method was used to get accurate speed for deadreckoning, before GPS was really usable on land.. OMG, I'm old.

Possible problems areas - dirt, debouncing the switch, timing of arduino. But these sound simple in comparison.

  [1]: https://en.wikipedia.org/wiki/Optical_mouse "wikipedia"


message:
Connect Bluetooth remote control with Arduino

For a project I need to connect a **Bluetooth Remote control** with an **Arduino Nano**.

On the Arduino-side I have an [HC-05-Bluetooth module][1]. With the Android Application "Bluetooth Terminal" I can verify that the connection is ok, because I can send and receive Strings with an Android smartphone.

In the minimal example I send values from a sensor which is connected to my Arduino via bluetooth to the smartphone, which is working nice. So I guess the wiring is correct:

<!-- language: c -->

    void loop() {
      sensorValue = analogRead( sensorPin );
      cm = 10650.08 * pow( sensorValue, -0.935 ) - 10;
      Serial.println( cm );
      softSerial.println(cm);
      delay( 500 );
    }

Instead of sending sensor values, I need to connect said remote with the Arduino.

[![Picture of the remote][2]][2]

*(Picture shows the basic model of said remote control.)*

The remote control has the Bluetooth class `20258C` which means:

 - Major Device Class: Peripheral
 - Limited Discoverable Mode
 - Audio
 - Pointing device
 - Remote control

**Remote Control Bluetooth  Specifications:**

- BT Device Name: YL-BTM3-xxxxxx
- Supplier ID and Product ID: 0x0A5C / 0x4503
- Class of Device: 0x20258C

My Question is: How can I pair those two devices? I can get the remote control into "Pairing mode", by pressing 2 Buttons. But how do I pair the Arduino-Bluetooth-module with this remote-control? Is it possible at all?

Best regards

  [1]: http://www.exp-tech.de/media/archive/gm/service/datasheet/HC-Serial-Bluetooth-Products.pdf
  [2]: https://i.stack.imgur.com/KUFzI.jpg

body:
This should be a comment, but..

For starters, you'll need to do the pairing from the Arduino with the HC-05 in master mode.

Check [this][1] out.

  [1]: https://alselectro.wordpress.com/2014/10/21/bluetooth-hc05-how-to-pair-two-modules/


message:
How to integrate ESP8266

Just, to make sure how it works:

 - I will connect the module to Arduino
 - it will create AP to which I can connect and send commands via HTTP

So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?

Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID (the PC will just communicate over regular network)?
Is it possible to communicate bidirectional somehow?

body:
> So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?

If you set the ESP8266 in AP you can connect to it with every wifi capable device.

You can control an ESP8266 with just an Arduino, but you I would not recommend using your Arduino as the power supply. If I remember correctly the mega's VCC pins are rated for 200mA which may or may not be enough for your ESP8266 I'm not sure, but I would recommend using another power supply for the ESP8266.

> Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID

Yes that is possible.

> Is it possible to communicate bidirectional somehow?

I am not exactly sure what you want, but it is possible to communicate in both directions. Assuming you know the local IP address of your ESP8266, you could for example send an HTTP request to it using any browser to which the ESP8266 can reply with anything.

Your ESP8266 can also send data to your computer, but it would require some program on your computer listening for incoming connections. Also possible, but more difficult.

At last I would like to tell you that driving an ESP8266 with an Arduino is like driving a Ferrari with the engine from a tuk tuk. It will move, but you will never use all of it's features. I don't know which version of the ESP8266 you have, but there are versions out there that can be programmed via USB just as your Arduino and you can just use the Arduino IDE and all of it's features like the Arduino language.


body:
Just wanted to second what @larzz11 says in the last para.  If you don't need the ADC's, running Arduino code on the device is definitely the simplest/easiest way to use the device.  The AT command firmware is challenging to get working in a stable fashion.

Also just to re-affirm the power requirements of the ESP8266 is higher than the 3v3 supply on the Arduino—you'll need a step-down converter from a sufficiently powerful 5v supply, or separate power supply, to get it working consistently.

Bidirectional comms are definitely doable, but the limited SRAM on Arduino make string parsing a real challenge, and even handling relatively small responses/requests can hit up against the available SRAM.

One of the nice things about using Arduino on the ESP8266 is that the ESP8266 has 8 times the amount of SRAM, making that more feasible also.


message:
How to solve "error 2" from the Arduino MPU6050 accelerometer

I'm new to Arduino and Stack Exchange. I've been building a fitness tracker and am receiving a certain error in the serial monitor. The accelerometer seems the work, but it seems to go to sleep after a while. I'm using an Arduino Uno (for the time being), a Bluetooth HC-05 module and an MPU6050 accelerometer. I connect it to an app, Retroband to monitor the steps taken and calories burnt.

I've wired it like this:

Accelerometer:

     SDA-A4
     SCL-A5
     VCC-3.3v
     GND-GND

Bluetooth:

     VCC-3.3v
     GND-GND
     TX-2
     RX-3

Here is the code I'm using:

    #include <math.h>
    #include <Wire.h>
    #include <SoftwareSerial.h>

    /* Bluetooth */
    SoftwareSerial BTSerial(2, 3); //Connect HC-06. Use your (TX, RX) settings

    /* time */
    #define SENDING_INTERVAL 1000
    #define SENSOR_READ_INTERVAL 50
    unsigned long prevSensoredTime = 0;
    unsigned long curSensoredTime = 0;

    /* Data buffer */
    #define ACCEL_BUFFER_COUNT 125
    byte aAccelBuffer[ACCEL_BUFFER_COUNT];
    int iAccelIndex = 2;

    /* MPU-6050 sensor */
    #define MPU6050_ACCEL_XOUT_H 0x3B // R
    #define MPU6050_PWR_MGMT_1 0x6B // R/W
    #define MPU6050_PWR_MGMT_2 0x6C // R/W
    #define MPU6050_WHO_AM_I 0x75 // R
    #define MPU6050_I2C_ADDRESS 0x68

    typedef union accel_t_gyro_union {
      struct {
        uint8_t x_accel_h;
        uint8_t x_accel_l;
        uint8_t y_accel_h;
        uint8_t y_accel_l;
        uint8_t z_accel_h;
        uint8_t z_accel_l;
        uint8_t t_h;
        uint8_t t_l;
        uint8_t x_gyro_h;
        uint8_t x_gyro_l;
        uint8_t y_gyro_h;
        uint8_t y_gyro_l;
        uint8_t z_gyro_h;
        uint8_t z_gyro_l;
      } reg;

      struct {
        int x_accel;
        int y_accel;
        int z_accel;
        int temperature;
        int x_gyro;
        int y_gyro;
        int z_gyro;
      } value;
    };

    void setup() {
      int error;
      uint8_t c;

      Serial.begin(9600);
      Wire.begin();
      BTSerial.begin(9600);  // set the data rate for the BT port

      // default at power-up:
      // Gyro at 250 degrees second
      // Acceleration at 2g
      // Clock source at internal 8MHz
      // The device is in sleep mode.
      //
      error = MPU6050_read (MPU6050_WHO_AM_I, &c, 1);
      Serial.print(F("WHO_AM_I : "));
      Serial.print(c,HEX);
      Serial.print(F(", error = "));
      Serial.println(error,DEC);

      // According to the datasheet, the 'sleep' bit
      // should read a '1'. But I read a '0'.
      // That bit has to be cleared, since the sensor
      // is in sleep mode at power-up. Even if the
      // bit reads '0'.
      error = MPU6050_read (MPU6050_PWR_MGMT_2, &c, 1);
      Serial.print(F("PWR_MGMT_2 : "));
      Serial.print(c,HEX);
      Serial.print(F(", error = "));
      Serial.println(error,DEC);

      // Clear the 'sleep' bit to start the sensor.
      MPU6050_write_reg (MPU6050_PWR_MGMT_1, 0);

      initBuffer();
    }

    void loop() {
      curSensoredTime = millis();

      // Read from sensor
      if(curSensoredTime - prevSensoredTime > SENSOR_READ_INTERVAL) {
        readFromSensor();  // Read from sensor
        prevSensoredTime = curSensoredTime;

        // Send buffer data to remote
        if(iAccelIndex >= ACCEL_BUFFER_COUNT - 3) {
          sendToRemote();
          initBuffer();
          Serial.println("------------- Send 20 accel data to remote");
        }
      }
    }

    /**************************************************
     * BT Transaction
     **************************************************/
    void sendToRemote() {
      // Write gabage bytes
      BTSerial.write( "accel" );
      // Write accel data
      BTSerial.write( (char*)aAccelBuffer );
      // Flush buffer
      //BTSerial.flush();
    }

    /**************************************************
     * Read data from sensor and save it
     **************************************************/
    void readFromSensor() {
      int error;
      double dT;
      accel_t_gyro_union accel_t_gyro;

      error = MPU6050_read (MPU6050_ACCEL_XOUT_H, (uint8_t *) &accel_t_gyro, sizeof(accel_t_gyro));
      if(error != 0) {
        Serial.print(F("Read accel, temp and gyro, error = "));
        Serial.println(error,DEC);
      }

      // Swap all high and low bytes.
      // After this, the registers values are swapped,
      // so the structure name like x_accel_l does no
      // longer contain the lower byte.
      uint8_t swap;
      #define SWAP(x,y) swap = x; x = y; y = swap
      SWAP (accel_t_gyro.reg.x_accel_h, accel_t_gyro.reg.x_accel_l);
      SWAP (accel_t_gyro.reg.y_accel_h, accel_t_gyro.reg.y_accel_l);
      SWAP (accel_t_gyro.reg.z_accel_h, accel_t_gyro.reg.z_accel_l);
      SWAP (accel_t_gyro.reg.t_h, accel_t_gyro.reg.t_l);
      SWAP (accel_t_gyro.reg.x_gyro_h, accel_t_gyro.reg.x_gyro_l);
      SWAP (accel_t_gyro.reg.y_gyro_h, accel_t_gyro.reg.y_gyro_l);
      SWAP (accel_t_gyro.reg.z_gyro_h, accel_t_gyro.reg.z_gyro_l);

      // Print the raw acceleration values
      Serial.print(F("accel x,y,z: "));
      Serial.print(accel_t_gyro.value.x_accel, DEC);
      Serial.print(F(", "));
      Serial.print(accel_t_gyro.value.y_accel, DEC);
      Serial.print(F(", "));
      Serial.print(accel_t_gyro.value.z_accel, DEC);
      Serial.print(F(", at "));
      Serial.print(iAccelIndex);
      Serial.println(F(""));

      if(iAccelIndex < ACCEL_BUFFER_COUNT && iAccelIndex > 1) {
        int tempX = accel_t_gyro.value.x_accel;
        int tempY = accel_t_gyro.value.y_accel;
        int tempZ = accel_t_gyro.value.z_accel;
        /*
        // Check min, max value
        if(tempX > 16380) tempX = 16380;
        if(tempY > 16380) tempY = 16380;
        if(tempZ > 16380) tempZ = 16380;

        if(tempX < -16380) tempX = -16380;
        if(tempY < -16380) tempY = -16380;
        if(tempZ < -16380) tempZ = -16380;

        // We dont use negative value
        tempX += 16380;
        tempY += 16380;
        tempZ += 16380;
        */
        char temp = (char)(tempX >> 8);
        if(temp == 0x00)
          temp = 0x7f;
        aAccelBuffer[iAccelIndex] = temp;
        iAccelIndex++;
        temp = (char)(tempX);
        if(temp == 0x00)
          temp = 0x01;
        aAccelBuffer[iAccelIndex] = temp;
        iAccelIndex++;

        temp = (char)(tempY >> 8);
        if(temp == 0x00)
          temp = 0x7f;
        aAccelBuffer[iAccelIndex] = temp;
        iAccelIndex++;
        temp = (char)(tempY);
        if(temp == 0x00)
          temp = 0x01;
        aAccelBuffer[iAccelIndex] = temp;
        iAccelIndex++;

        temp = (char)(tempZ >> 8);
        if(temp == 0x00)
          temp = 0x7f;
        aAccelBuffer[iAccelIndex] = temp;
        iAccelIndex++;
        temp = (char)(tempZ);
        if(temp == 0x00)
          temp = 0x01;
        aAccelBuffer[iAccelIndex] = temp;
        iAccelIndex++;
      }

      // The temperature sensor is -40 to +85 degrees Celsius.
      // It is a signed integer.
      // According to the datasheet:
      // 340 per degrees Celsius, -512 at 35 degrees.
      // At 0 degrees: -512 - (340 * 35) = -12412
    //  Serial.print(F("temperature: "));
    //  dT = ( (double) accel_t_gyro.value.temperature + 12412.0) / 340.0;
    //  Serial.print(dT, 3);
    //  Serial.print(F(" degrees Celsius"));
    //  Serial.println(F(""));

      // Print the raw gyro values.
    //  Serial.print(F("gyro x,y,z : "));
    //  Serial.print(accel_t_gyro.value.x_gyro, DEC);
    //  Serial.print(F(", "));
    //  Serial.print(accel_t_gyro.value.y_gyro, DEC);
    //  Serial.print(F(", "));
    //  Serial.print(accel_t_gyro.value.z_gyro, DEC);
    //  Serial.println(F(""));
    }

    /**************************************************
     * MPU-6050 Sensor read/write
     **************************************************/
    int MPU6050_read(int start, uint8_t *buffer, int size)
    {
      int i, n, error;

      Wire.beginTransmission(MPU6050_I2C_ADDRESS);

      n = Wire.write(start);
      if (n != 1)
        return (-10);

      n = Wire.endTransmission(false); // hold the I2C-bus
      if (n != 0)
        return (n);

      // Third parameter is true: relase I2C-bus after data is read.
      Wire.requestFrom(MPU6050_I2C_ADDRESS, size, true);
      i = 0;
      while(Wire.available() && i<size)
      {
        buffer[i++]=Wire.read();
      }
      if ( i != size)
        return (-11);
      return (0); // return : no error
    }

    int MPU6050_write(int start, const uint8_t *pData, int size)
    {
      int n, error;

      Wire.beginTransmission(MPU6050_I2C_ADDRESS);

      n = Wire.write(start); // write the start address
      if (n != 1)
        return (-20);

      n = Wire.write(pData, size); // write data bytes
      if (n != size)
        return (-21);

      error = Wire.endTransmission(true); // release the I2C-bus
      if (error != 0)
        return (error);
      return (0); // return : no error
    }

    int MPU6050_write_reg(int reg, uint8_t data)
    {
      int error;
      error = MPU6050_write(reg, &data, 1);
      return (error);
    }

    /**************************************************
     * Utilities
     **************************************************/
    void initBuffer() {
      iAccelIndex = 2;
      for(int i=iAccelIndex; i<ACCEL_BUFFER_COUNT; i++) {
        aAccelBuffer[i] = 0x00;
      }
      aAccelBuffer[0] = 0xfe;
      aAccelBuffer[1] = 0xfd;
      aAccelBuffer[122] = 0xfd;
      aAccelBuffer[123] = 0xfe;
      aAccelBuffer[124] = 0x00;
    }

This is the error I got in serial monitor:

        WHO_AM_I : 0, error = 2
    PWR_MGMT_2 : 0, error = 2
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, -3840, at 2
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 8
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 14
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 20
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 26
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 32
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 38
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 44
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 50
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 56
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 62
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 68
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 74
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 80
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 86
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 92
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 98
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 104
    Read accel, temp and gyro, error = 2
    accel x,y,z: 2969, 409, 123, at 110
    Read accel, temp and gyro, error = 2
    accel x,y,z: -26357, -26367, 31488, at 116

I'm not too good at Arduino, and any help will be immensely appreciated.

body:
You have a problem that you can see (the error 2) and a theory about what might be causing it (the accelerometer going to sleep). That's a great place to start from!

I have a few of suggestions to make:

* Collect documentation for the components you are using, a data sheet for the accelerometer, tutorials and instructions for the code to drive it, etc.

 A search on:

    `MPU6050 accelerometer data sheet`

  is likely to get you lots of links to sites hosting data sheets for the accelerometer. With luck you'll be able to find the actual vendor and in addition to the data sheet you may able to find application notes there as well.

 For the library, you may find a tutorial or an API description on the site where you downloaded it. You can also do a search on something like:

 `MPU6050 accelerometer tutorial`

 to find suggestions for how to get started with the device and the code to use it. Tutorials often have sections on testing and avoiding common pitfalls with the device.

* Once you have some documentation see what you can learn about the error. Who generates "error 2?" What does it mean? When does it occur? Once you understand the problem, the answer may be obvious.

* Create minimal test cases. The code sample above is a lot for you, or us, to make sense of and then to test/debug. Pare your code down (or build it up, depending where you are in the process and how you like to work on problems) until you have the **minimum** code needed to test the accelerometer.

 Do you see the problem in that code? If you do, then you have many fewer possible problems to look at. If you don't, then add the next piece – perhaps in this case, try to exercise the condition that "error 2" is supposed to report (does it still seem likely that "going to sleep" is the problem?

If you're still stumped at this point you've got the resources at hand to post a great question and the evidence that you've worked on it and understand it for yourself will go a long way towards establishing good will with the people who are trying to help you find answers.

Since this is (potentially) a hardware **and** a software problem, be sure to include an accurate schematic, or photo, of how your project is put together. If you are using someone else's schematic be especially cautious of any potential differences!


body:
From examination of the sketch, the error '2' that you are seeing is returned from `MPU6050_read()`, by the line

    n = Wire.endTransmission(false); // hold the I2C-bus

Looking at the reference for the [Wire][1] library, [`endTransmission()`][2] returns 2 when

> 2:received NACK on transmit of address

So, when you transmit to the MPU6050, the MPU6050 appears to be returning a Not Acknowledged (NACK) packet.

Why a NACK is being returned is not too clear. From [Mpu6050 - error 2 - endTransmission][3]:

> It means the chips is either not connected (or not correctly) or the wrong address was sent.

From the [MPU-6050 page on Arduino Playground][4], it seems that the address should be 0x68 or 0x69

> The pin "AD0" selects between I2C address 0x68 and 0x69. That makes it possible to have two of these sensors in a project. Most breakout boards have a pullup or pulldown resistor to make AD0 default low or high. Connect AD0 to GND or 3.3V for the other I2C address.

What is AD0 connected to? You do not mention that, in your wiring list for the MPU-6050. If you connect AD0 to GND then address 0x68 is used, if it is to 3.3V then the address is 0x69. From [MPU6050 SparkFun Breakout to Arduino Uno - No Communication][5].

> AD0 must be connected to ground or 3.3V (with solder jumper). Connect it to ground for I2C address 0x68.
SCL and SDA are connected directly to the Arduino, but you could add extra pull-up resistors to the 3.3V. The resistors could be 4k7 or 10k (the board already has 10k pull-up resistors, but I prefer 4k7).
You don't need the INT, you could leave it open.
The CLKIN and FSYNC can be tied to ground, because they are not used.

I would suggest checking your wiring, and look for any loose contacts on the MPU6050 board.

  [1]: https://www.arduino.cc/en/Reference/Wire
  [2]: https://www.arduino.cc/en/Reference/WireEndTransmission
  [3]: http://forum.arduino.cc/index.php?topic=238919.0
  [4]: http://playground.arduino.cc/Main/MPU-6050
  [5]: http://forum.arduino.cc/index.php?topic=103408.15