message:
HardwareSerial - check for overflow

The SoftwareSerial library has a built-in [Overflow][1] function, but the [Serial][2] library does not.  Is there a simple way to check for a data buffer overflow on a hardware serial port?

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerialOverflow
  [2]: https://www.arduino.cc/en/Reference/Serial

body:
A look at `HardwareSerial_private.h` shows incoming bytes are always read (interrupt-based), regardless of what your code is doing. So we can't set up a hardware interrupt to notify us when the chip's RX register has overflowed, because such an interrupt would depend on overflow flags but these flags never become set because, like I said, bytes are always read. It also shows that while all incoming bytes are read, not all are added to the 64-byte Serial buffer i.e. a byte may be read but if the buffer is full, nothing else happens; it is simply read to clear hardware flags. So the only (direct) way I can think of is to constantly poll `Serial.available()` in `loop()` to check if the number of bytes available for reading is equal to 64. If this condition yields TRUE, then you may safely conclude that the Serial buffer is full and about to overflow. This should suffice:

        void loop(){
            //your code
            if (Serial.available() == SERIAL_RX_BUFFER_SIZE){ // Just to be general, 64 bytes in most cases
                //buffer is overrun, do what u will
            }
        }

You could make some changes to `HardwareSerial_private.h` to get something like the overflow() method of SoftwareSerial. The relevant lines are:

        if (i != _rx_buffer_tail) {
            _rx_buffer[_rx_buffer_head] = c;
            _rx_buffer_head = i;
        }

The snippet above ensures that the current write position is not equal to the tail of the ring buffer (i.e. if we are about to overwrite a character in the buffer), before writing the incoming byte to the buffer. An `else` block could be added to set some global variable to indicate overflow. This global variable would have to be cleared when `Serial.read()` is called.


sender: user

message:
Permanent connections with Arduino Due

The Arduino Uno (for some models) has the ability to dislodge its IC chip. You can mount this on a piece of perfboard and, in essence, have a permanent connection. I will need the beefier Arduino Due, but I do not know how to make permanent connections with this device. Is there any way to form some kind of permanent connection with this board?

sender: assistant

body:
What it sounds like you want is an Arduino Due footprint prototyping shield.

[Arduino make one](https://store.arduino.cc/index.php?main_page=product_info&products_code=A000080), although it is out of stock, but it gives you an idea of what you are looking for. There are plenty of other designs out there for purchase of varying degrees of complexity.

You solder the pins in place and mount it on top of your Due just like any shield, and solder your wires and components in where you want them.

An alternative option, of course, is to step away from Arduino and investigate some of the many other chips from other manufacturers out there that are considerably more powerful than the 8-bit ATMegas used on the low-end Arduinos, and yet are still available in a DIP footprint - chips like the PIC32MX1xx/2xx series from Microchip - 28 pin DIP (just like the 328P) yet 50MHz, 32-bit power.  Yes, it will be a bit of a learning curve, but there are helpful options out there that can assist you, like the [chipKIT](http://chipkit.net) system including the handy [DP32 board from Digilent](http://www.digilentinc.com/Products/Detail.cfm?Prod=CHIPKIT-DP32).


body: You can disolder the female pin headers from pcb and make permanent connections on the remaining holes.


body:
I think the best thing you can do with this, is that you use temporary wires to connect and test the application and later, when you'll come to part, where you should "make-a-solid", you just solder these wires to the bottom, where pin headers are. I think this is the simplest way to do it.

If you want to do it a bit better, desolder female header pins and solder cables to those holes. It's more electronics-approved that way.

Or the simplest (but not the brighest): Jumper wires can be glued into female header pins, but I strongly unrecommend this option, as same as making a shield for this.

There's another(and most elegant too!) option of making a PCB version of arduino: Add the AtMega, few passive components and proper pads, to solder wires on.


message:
How do I connect multiple pinhole cameras and take photos and video at the press of a button?

I am trying to set up a 4 cameras which can take videos/photos at the press of a button.

Things which I will need:

 1. 4 micro cameras(the ones which are very small in size) with good
    shutter speed and sensor. The cameras will often travel at 20 to
    30mph. So I guess good shutter speed is needed.
 2. 2 Push buttons. One will start and stop taking pictures really fast, and the other will do the same for video
 3. Battery which can last atleast taking 5 images/1 min of video recording.
 3. 4 Microsd cards and the connectors. Is there anyway I would be able to set up a common adapter to all these cards, so when connected to a computer it will show up as 4 different drives?

So I think I can make the set up using this: http://www.arducam.com/
But can it take images really fast. I couldn't see any information regarding this. It should be able to take like 4 images per second. Also it would be awesome if this set up can somehow support taking videos.

Now another thing I need is a push button which will start taking the photos and stop taking it.

This whole thing should operate from a battery.

Mostly I want to know is the list of products which will work or the specs to look for when choosing the products. Also I would like to know if this is the best way to go for  a project like this. This thing will be more like a toy, so I don't want to use really expensive parts for this. Also I don't want a gopro. I want to make this whole set up myself.

Let me know if you need to know more details about this.

body:
Arduinos and Cameras do not mix well at all.  It's all down to the sheer quantity of data involved in pictures.

Take for instance a typical VGA image - 640x480 pixels at 24-bit (3 byte) colour depth.  One single picture requires 640x480x3 = 921600 bytes just to store it.

Add to that the fact that most small cameras include hardware JPEG compression which the Arduino really has no hope of being able to handle, and you just can't do anything with it.

Most camera modules use a system called [CSI-3](http://mipi.org/specifications/camera-interface) (Camera Serial Interface version 3) for streaming the raw data from the CCD elements into the target.  That allows for high speed data transfer of the whole frame at a speed that is able to support video.  If you think about video as 25 frames per second, and raw data, that means that the data is being transferred from the CCD elements in total at arouns 22 MiB/s - there is absolutely no way that an Arduino can deal with that kind of data.  So cameras that attach to an Arduino have their own controller chip that compresses the image to JPEG and streams it out through a much slower interface - typically RS232.  All the Arduino can then do is tell the camera "Take a picture for me" at which point an image is captured and compressed, and then the Arduino receives the JPEG data through serial (slowly) and stores it on an SD card (also slowly). It can't do anything else with it.

To crunch those numbers - assume that the compressed VGA image from the camera's processor chip is 100,000 bytes (I took a typical photo, scaled it to 640x480 and saved it with 90% JPEG compression and it was roughly that size).  At 9600 baud you get 960 bytes per second. 100,000 / 960 = 104 seconds.

That is how long it would take to transfer one single image through the Arduino.

If the camera has a higher speed UART, say 115200 baud (11520 Bps), that would then give you 100,000/11,520 = 8.7 seconds.

So no, using an Arduino to control cameras in that way just isn't possible.

Instead you need a system that can talk CSI-3 directly - something with a direct camera connection, such as the Raspberry Pi.  Another alternative is any embedded computer with enough processing power and USB ports to connect cheap USB webcams to.  Again the Raspberry Pi would do - especially the newer version 2 with the quad core processor.


message:
GPS library for Proteus

I am working on a project in which I have to connect my Arduino with a GPS module. In this project I need to get longitude, latitude, time and date from the GPS module and need to send these values via USB to a computer.

On this computer, I am going to design software in Microsoft Visual Studio 2010, which will receive this data and display it on a map.

Now, before designing it in hardware, I want to simulate it on Proteus. I have searched in Proteus but there's no GPS module in it, so does anyone know any GPS module library for Proteus?

body:
I have found the solution to my question so I thought to post it here so that others could also get benefit out of it. Here's the link to [GPS Library for Proteus - A complete step by step tutorial on How to download GPS Library for Proteus][1].

From this link you can download the GPS Library which you need to add to the libraries folder of your Proteus software and you will have the GPS module in Proteus and you can design your simulation quite easily. More details are given in this link.

  [1]: http://www.theengineeringprojects.com/2015/12/gps-library-proteus.html


body:
If you will be using the computer to interface, **you don't really need Arduino in the middle**.

You can hook the GPS module to the computer using a USB-UART bridge like one below:

[![USB to serial][1]][1]

The usual GPS modules (ebay or other hobby stores) output NMEA sentences over their serial port. Check the datasheet of your GPS module for the baud rate and the RX/TX pins. Connect the RX and TX lines of your GPS to the USB-serial module and you should be able to see NMEA output on a terminal emulator (set to right baud).

Once you see NMEA sentences over a terminal emulator, you can parse those in your application directly (bypassing terminal emulator) instead of using an Arduino.

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


message:
Arduino Uno - why doesn't memory leak crash the program?

I wrote this test program:

<!-- language: c -->

    void loop()
    {
        digitalWrite(13,1);
        delay(300);
        digitalWrite(13,0);
        delay(300);
        void *a = malloc(10000000000000000000000000000000000000000);
    }

Curiously, the LED keeps blinking and so it means the loops continues.

My question is how can it continue when it runs out of heap memory like that?

body:
`malloc()` by itself generally doesn't *crash* a program.  It attempts to allocate the requested amount of memory, and if it can it will.  If it can't (there isn't enough memory available) then it won't allocate anything and will just return NULL.

By trying to allocate more memory than you have it will just fail every time and no memory will be allocated - thus you don't actually have a memory leak, so your program doesn't fail.

The main reason for crashing is a phenomenon called *stack smashing* where the memory area used by `malloc()` (known as the *heap*) and the memory area for the stack (used by local variables and for storing the contents of registers during function calls) collide with one another and one corrupts the other.  For instance, if the *return address* of the current function in the stack is corrupted, when the function finishes it will return to the wrong memory location and who knows what may happen then?  Wrong instructions will be executed for sure.

For instance, try this program out instead:

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

    void loop() {
        char *a = (char *)malloc(10);
        if (a != NULL) {
            Serial.println("Allocated 10 bytes");
        } else {
            Serial.println("Allocation failed");
        }
    }

If all goes well you should see lots of "Allocated 10 bytes" followed by some "Allocation failed".  Since the memory is now full there is a chance that it may now crash as the stack and heap collide - in which case you would expect to see the "Allocation failed" messages stop.


body:
Allocating memory doesn't really do much to it except for (typically) writing some bookkeeping information into its header - a portion the caller doesn't (isn't supposed to...) see. In particular, that bit of memory doesn't become unavailable for anything (other than further allocation).

Malloc maintains a buffer between the stack pointer location and the heap, from which it will not allocate. This tends to ( <--- note "weasel words") prevent a heap vs. stack collision

If the stack grows down into memory that was already allocated, the stack will over-write the data in some allocated block. It is impossible to say what effect that will have on further program operation without knowing a whole lot more about the program, and quite possibly, about the contents and timing of any data that has yet to be received.

If the heap grows upward into the stack, and program writes into that allocated block, it will be over-writing parts of it's own stack with, again, unpredictable (without a lot more information) results.

A simple test program that merely allocates lots of small blocks will have a good chance of running forever, or at least until the `malloc()` call returns a NULL pointer when it is out of memory to allocate. At that point, if the test program is checking for the NULL return, there is a good chance the program can print its message and end normally. But if the program blindly writes into the memory `malloc()` returns, and writes through the eventual NULL pointer, then low-memory will get corrupted. Low memory is typically the location of the interrupt vector table (and the Arduinos' AVR processors are no exception), some interrupt is likely to get vectored to somewhere other than its proper service routine, and abnormal program operation will result; most likely, a crash.


message:
WARNING: Category '' in library *any library* is not valid. Setting to 'Uncategorized'

I'm using Ubuntu 14.04 with arduino Galileo and the newest arduino IDE from arduino.cc and every time I compile I got this warnings with *any library* in place of EEPROM, SD, Wire, Wifi and a lot of others.

When I check the boards manager I got the following:

Invalid library found in /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire: /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire

Anyone knows how to solve this?

body:
Edit or add library.properties to that folder so that you specify a valid category.

Example of library.properties:

    name=WebServer
    version=1.0
    author=Cristian Maglie <c.maglie@example.com>, Pippo Pluto <pippo@example.com>
    maintainer=Cristian Maglie <c.maglie@example.com>
    sentence=A library that makes coding a Webserver a breeze.
    paragraph=Supports HTTP1.1 and you can do GET and POST.
    category=Communication
    url=http://example.com/
    architectures=avr


body:
From: https://www.bountysource.com/issues/29336127-one-wire-library-still-in-v2-3-0-causes-useless-warning

> The Arduino library manager still defaults to v2.3.0, which causes the
> IDE to raise the following warning on compile :
>
> WARNING: Category '' in library OneWire is not valid. Setting to
> 'Uncategorized'

Solution (In 1.6.12):

 1. Sketch -> Include Library -> Manage Libraries
 2. In the upper-right "Filter Your Search" box enter (without the quotes): "OneWire"
 3. Click the "OneWire by Jim Studt, Tom P..."
 4. Select version 2.3.1 (or newer)
 5. Click "Install"


body:
As sated above you need to "Edit or add library.properties to that folder so that you specify a valid category."

This link has some good info on the structure of the file: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

From that link:

library.properties file format

The library.properties file is a key=value properties list. Every field in this file is UTF-8 encoded. The available fields are:

    **name** - the name of the library
    version - version of the library. Version should be semver compliant. 1.2.0 is correct; 1.2 is accepted; r5, 003, 1.1c are invalid
    **author** - name/nickname of the authors and their email addresses (not mandatory) separated by comma ","
    **maintainer** - name and email of the maintainer
    **sentence** - a sentence explaining the purpose of the library
    **paragraph** - a longer description of the library. The value of sentence always will be prepended, so you should start by writing the second sentence here
    **category** - if present, one of these: "Display", "Communication", "Signal Input/Output", "Sensors", "Device Control", "Timing", "Data Storage", "Data Processing", "Other"
    **url** - the URL of the library project, for a person to visit. Can be a github or similar page as well
    architectures - a comma separated list of architectures supported by the library. If the library doesn’t contain architecture specific code use “*” to match all architectures
    **dot_a_linkage** - (available from IDE 1.6.0 / arduino-builder 1.0.0-beta13) when set to true, the library will be compiled using a .a (archive) file. First, all source files are compiled into .o files as normal. Then instead of including all .o files in the linker command directly, all .o files are saved into a .a file, which is then included in the linker command.
    **includes** - (available from IDE 1.6.10) a comma separated list of files to be added to the sketch as #include <...> lines. This property is used with the "Include library" command in the IDE. If the property is undefined all the headers files (.h) on the root source folder are included.


message:
Can't make Wee serial WiFi work with Arduino Uno

I'm trying to plug a [Wee serial WiFi][1] module on my Arduino Uno, through an [XBee shield][2] .

[![Wee in XBee shield][3]][3]

I'm simply trying to make work [the example from the library][4].

All I get is

    setup begin
    FW Version:
    to station err
    Join AP failure
    setup end

The code i'm using :

    #include <SoftwareSerial.h>
    #include <doxygen.h>
    #include <ESP8266.h>

    SoftwareSerial mySerial(3, 2); /* RX:D3, TX:D2 */
    ESP8266 wifi(mySerial);

    #define SSID "yuflowoffice"
    #define PASSWORD "cashless"

    void setup(void) {
      Serial.begin(9600);
      mySerial.begin(115200);
      Serial.print("setup begin\r\n");

      Serial.print("FW Version: ");
      Serial.println(wifi.getVersion().c_str());

      if (wifi.setOprToStation()) {
        Serial.print("to station ok\r\n");
      } else {
        Serial.print("to station err\r\n");
      }
      delay(1500);

      if (wifi.joinAP(SSID, PASSWORD)) {
        Serial.print("Join AP success\r\n");
        Serial.print("IP: ");
        Serial.println(wifi.getLocalIP().c_str());
      } else {
        Serial.print("Join AP failure\r\n");
      }

      Serial.print("setup end\r\n");
    }

    void loop(void) {
    }

What can I do?

  [1]: http://wiki.iteadstudio.com/Wee_Serial_WIFI_Module
  [2]: https://hackspark.fr/fr/xbee-shield.html
  [3]: https://i.stack.imgur.com/GsC52.jpg
  [4]: https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/examples/ConnectWiFi/ConnectWiFi.ino

body:
A look at https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/ESP8266.h shows that when you pass a `SoftwareSerial` object to the ESP8266 constructor, a default baud rate of 9600 is also passed to it. Also, the library source file shows that, in the constructor, the `begin()` method of the `SoftwareSerial` object you passed (myserial) is called with 9600 baud. Thus, this line in your code:

        mySerial.begin(115200);

is a duplicate, albeit one with a different baud rate, thus rendering the constructor's call of `mySerial.begin()` useless, since your call comes after the constructor's. If you are certain that 115200 is the right baud rate for the hardware, then you should get rid of the line above and instead pass the baud rate to the constructor like this:

        ESP8266 wifi(mySerial, 115200);

Replace 115200 with any baud rate you discover to be the right one for the AT commands. You also need to uncomment the line in ESP8266.h in your library:

        //#define ESP8266_USE_SOFTWARE_SERIAL

and then save, since you are using SoftwareSerial to communicate with the module.


message:
Logging to multiple destinations (serial & SD card)

I am building a rover using an Arduino Mega and an Arduino Uno. The Mega has a sensor shield that has an SD card slot. The intent is for the rover to be autonomous, and I currently send logging info to the serial port (to log actions like boot, diagnostics, etc.)

Is there a simple way to redirect this output to BOTH the serial and the SD card? I would be happy with just a single file with lines added for each entry.

My complication here is to prevent using `Serial.println` as well as `SD.println` as two separate commands. Is there any other way around this?

body:
The simplest thing you can do is to create a simple function that performs both tasks for you.  However, there are certain caveats that you should look out for.  The most basic function would be:

    void log(const char *msg) {
        Serial.println(msg);
        myFile.println(msg);
    }

However that is not the best way of doing it since that requires all your messages to be in RAM.  So you should really use the `__FlashStringHelper` type as well as an *overload* function so you can use the `F()` macro to save RAM:

    void log(const char *msg) {
        Serial.println(msg);
        myFile.println(msg);
    }

    void log(const __FlashStringHelper *msg) {
        Serial.println(msg);
        myFile.println(msg);
    }

And that will pick the right version of `log` depending on what you pass.  But what if you want to pass some variables, like numbers?  Overloading can help again here.  Another pair of functions now that take two parameters instead of one:

    void log(const char *msg) {
        Serial.println(msg);
        myFile.println(msg);
    }

    void log(const __FlashStringHelper *msg) {
        Serial.println(msg);
        myFile.println(msg);
    }

    void log(const char *msg, int v) {
        Serial.print(msg);
        Serial.print(" ");
        Serial.println(v);
        myFile.print(msg);
        myFile.print(" ");
        myFile.println(v);
    }

    void log(const __FlashStringHelper *msg, int v) {
        Serial.print(msg);
        Serial.print(" ");
        Serial.println(v);
        myFile.print(msg);
        myFile.print(" ");
        myFile.println(v);
    }

So now you have 4 functions called `log`, and they can be used in these different ways:

    log("This is a message"); // Could be a char * variable
    log(F("This is a message"));
    log("The temperature is:", temp);
    log(F("The temperature is:", temp);

And of course you can keep expanding and expanding the parameters in different ways for different combinations of parameters.  Just be warned that for some combinations of parameters the compiler won't be able to work out which is the right function to call (for instance if you have one that takes a `long` and one that takes a `byte` in the same place and you just pass a numeric literal), so you have to think carefully about how you arrange your parameters.


message:
Could not read ID via SWD with Arduino

So I'm trying to read a bit of data via SWD. I've tried two chips as target - LPC1110 and STM32F030F4 (the first of them I used for other schematic, but I've reset the flash to make sure the pins are not configured improperly).

I use Arduino as a host. I wire D3 to SWCLK and D4 to SWDIO (with pull-up to 3.3V line). I fail miserably with both chips - i.e. when I expect some ACK be read - it only shows HIGH state on the line all the time.

Here is my code. Could anyone have a look and tell where I went wrong:

    int swdck = 3;
    int swdio = 4;

    void setup() {
      pinMode(swdck, OUTPUT);
      digitalWrite(swdck, HIGH);
      pinMode(swdio, INPUT);
      digitalWrite(swdio, HIGH);
      Serial.begin(9600);
    }

    // write some bits from X (least significant first) to SWD
    void clockOut(int x, int bits) {
      pinMode(swdio, OUTPUT);
      while (bits > 0) {
        digitalWrite(swdck, LOW);
        digitalWrite(swdio, (x & 1) ? HIGH : LOW);
        delay(1);
        digitalWrite(swdck, HIGH);
        delay(1);
        bits--;
        x >>= 1;
      }
      pinMode(swdio, INPUT);
      digitalWrite(swdio, HIGH);
    }

    // read some bits from SWD, least significant first
    int clockIn(int bits) {
      pinMode(swdio, INPUT);
      digitalWrite(swdio, HIGH);
      int i, res;
      res = 0;
      for (i = 0; i < bits; i++) {
        digitalWrite(swdck, LOW);
        delay(1);
        if (digitalRead(swdio) == HIGH) {
          res += (1 << i);
        }
        digitalWrite(swdck, HIGH);
        delay(1);
      }
      return res;
    }

    void loop() {
      int x;
      // unlock sequence though it probably is not needed
      clockIn(26); clockIn(26); // more than 50 clocks
      clockOut(0xE79E, 16); // command to switch to SWD
      clockIn(26); clockIn(26);

      clockOut(0x25, 7); // 0b0100101 - request to read Debug-port-0, i.e. ID
      x = clockIn(5); // there should be ACK bits somewhere... but I get 0x1111
      clockIn(26); clockIn(26); // perform more readings for case anything is returned
      Serial.println(x);
      delay(1000);
    }

body:
I am not a SWD expert; it is several years since I read the spec. So I apologise if you are way ahead of me.

I believe ARM's SWD documentation, e.g. "ARM® Debug Interface v5 Architecture Specification" (ARM IHI 0031A) says that transfers are fixed length, starting with an 8 bits request.

The code:

    void clockOut(int x, int bits) {
      pinMode(swdio, OUTPUT);
      while (bits > 0) {
        ...
        bits--;
        ...
      }
      ...
    }

is invoked with `clockOut(0xE79E, 16)`

A packet request is 8 bits, followed by a response from the target. So this doesn't appear to follow the protocol.

Similarly `clockOut(0x25, 7)` appears to send 7 bits, which also looks wrong, and may explain why the read fails.

Further, there should be a 'turnaround bit' after sending the packet.

This code:

    void clockOut(int x, int bits) {
      pinMode(swdio, OUTPUT);
      ...
      pinMode(swdio, INPUT);
      digitalWrite(swdio, HIGH);
    }

looks like it is setting up to do that, however, it also needs to signal another clock pulse, e.g.:

    void clockOut(int x, int bits) {
      pinMode(swdio, OUTPUT);
      ...
      pinMode(swdio, INPUT);
      digitalWrite(swdio, HIGH);
      /* signal a clock pulse */
      digitalWrite(swdck, LOW);
      delay(1);
      digitalWrite(swdck, HIGH);
      delay(1);
     }

A SWD read should return 33 bits, so `x = clockIn(5);` looks a bit fragile.

Even so, it should get the three ACK bits. It should leave another pile of bits unread, which is what I mean by fragile.

However, `x = clockIn(5);` might be incorrect because of the short `clockOut(0x25, 7)` and lack of a turnaround bit.

Small points:

 - I'd change that `clockOut` `while` loop to be a `for` loop like `clockIn` to make it clear that it is running for a specific 'count' (bits) of bits to be transferred.
 - `delay(1)` seems to be a long time between bits. I don't remember any
   timing restrictions. However, I would expect the transfers to run
   10-100x faster.
 - IMHO `clockIn(26); clockIn(26);` seems to be an unnecessarily obscure way
   to generate the 50 cycle connection/reset sequence. I'd probably have
   a slightly simpler function than `clockIn` which only generates the
   connection/reset sequence.

Edit:
The statement `res += (1 << i);` in `clockIn` works.

However, I had to read it a couple of times to recognise that it is assembling a binary value, and not doing some tricky arithmetic. It is more common to use bitwise operators to assemble a binary value. It is only a small point of style, however `res |= (1 << i);` might be more clearly constructing a binary value, than `res += (1 << i);` because it can only ever effect one bit, and never many bits.


message:
Basic usage of Nick Gammon's Regexp library

I am using the following code modified from the examples. I get the count of matches but the actual value is not displayed

    #include <Regexp.h>

    void setup() {
        Serial.begin(115200);
        MatchState ms;
        char buf [100];
        char buf2 [100] = "The quick brown fox jumps over the lazy wolf";
        ms.Target (buf2);
        unsigned int count = ms.MatchCount ("[aeiou]");

        Serial.print ("Found ");
        Serial.print (count);
        Serial.println (" matches.");
        for (int j = 0; j < count; j++)
        {
              Serial.print ("Capture number: ");
              Serial.println (j, DEC);
              Serial.print ("Text: '");
              Serial.print (ms.GetCapture (buf, j));
              Serial.println ("'");
        }
    }
    void loop(){}

body:
You haven't defined any capture groups in your regexp.

The regexp `[aeiou]` will *match* any of those characters, but it won't *capture* them.  To capture you need to define a *capture group* which is a sequence of tokens surrounded by parenthesis.  For instance:

    ([aeiou])

In your test phrase "The quick brown fox jumps over the lazy wolf" that should match 11 times and capture each match, resulting in captures of *e u i o o u o e e a o*.

The reason why matching and capturing are two completely different things is so you can do things like `[aeiou]([aeiou])` which would capture the second vowel in a two vowel sequence. In your example it would match the *ui* of *quick* and capture just the *i*.


message:
Can external interrupts be OR'd together on the '328 (Uno)?

I'm thinking about how to handle a rotary encoder. I'm planning on using interrupts and would like to use both the 'A' and 'B' phase transitions to generate interrupts. I'm wondering if there is any reason why the signals couldn't be OR'd together to generate the interrupt so that I wouldn't need to consume both external interrupts for the encoder.

body:
Regarding the notion that “"internal" interrupt latency and/or software overhead is much higher than it is for the "external" interrupts”, it certainly is true that PCI (pin-change interrupts) libraries [`PinChangeInt.h` (deprecated)](https://github.com/GreyGnome/PinChangeInt/commit/ec745f854b2b807640341cf479f540bb8bb3fc2f) and [`EnableInterrupt.h`](https://github.com/GreyGnome/EnableInterrupt) have high software overhead.  By keeping track of former values, for each pin those libraries support separate callback routines for Rising, Falling, Change, High, and Low.  PCIs are grouped in sets of eight pins per interrupt vector, leading to 40 different cases of callback routines when a PCI fires.  That is, when a PCI occurs, the libraries quickly find out which set of pins changed – because that's what the hardware supports – but then they go through all eight pins on the vector one by one checking if it changed, and how it changed, then calling the callback associated with the particular pin and its particular state.

For reading pins of a rotary encoder, say a [KY-040](https://www.google.com/search?q=ky-040+rotary+encoder&biw=1095&bih=625&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwiN8-KEv4XKAhVU2mMKHVxYBPIQsAQIGw), the overhead described above can cause loss of 10%–20% of rotary counts.  If you are concerned about not losing counts, write your own `ISR()`-level interrupt service routine.  The example below illustrates a routine using `ISR()`; this example is from my [answer to previous question #18221](https://arduino.stackexchange.com/a/18221/3917), with some comments added here and there.  See that answer for discussion of the timing data that is this program's output.  (For rotary encoder quadrature-counting, see discussion below).

<!-- language: lang-c -->

    /*  rcTiming.ino -- JW, 30 November 2015 --
     * Uses pin-change interrupts on A0-A4 to time RC pulses
     *
     * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
     *
     */
    #include <Streaming.h>
    static   byte rcOld;        // Prev. states of inputs
    volatile unsigned long rcRises[4]; // times of prev. rising edges
    volatile unsigned long rcTimes[4]; // recent pulse lengths
    volatile unsigned int  rcChange=0; // Change-counter

    // Be sure to call setup_rcTiming() from setup()
    void setup_rcTiming() {
      rcOld = 0;
      // Note, if using an encoder without pullups on it,
      // change INPUT in next 2 lines to INPUT_PULLUP
      pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
      pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
      pinMode(A2, INPUT);
      pinMode(A3, INPUT);
      PCMSK1 |= 0x0F;       // Four-bit mask for four channels
      PCIFR  |= 0x02;       // clear pin-change interrupts if any
      PCICR  |= 0x02;       // enable pin-change interrupts
    }
    // Define the service routine for PCI vector 1
    ISR(PCINT1_vect) {
      byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
      byte changes = rcNew^rcOld;   // Notice changed bits
      byte channel = 0;
      unsigned long now = micros(); // micros() is ok in int routine
      while (changes) {
        if ((changes & 1)) {  // Did current channel change?
          if ((rcNew & (1<<channel))) { // Check rising edge
            rcRises[channel] = now;     // Is rising edge
          } else {              // Is falling edge
            rcTimes[channel] = now-rcRises[channel];
          }
        }
        changes >>= 1;      // shift out the done bit
        ++channel;
        ++rcChange;
      }
      rcOld = rcNew;        // Save new state
    }

    void setup() {
      Serial.begin(115200);
      Serial.println("Starting RC Timing Test");
      setup_rcTiming();
    }

    void loop() {
      unsigned long rcT[4]; // copy of recent pulse lengths
      unsigned int rcN;
      if (rcChange) {

        // Data is subject to races if interrupted, so off interrupts
        cli();   // Disable interrupts
        rcN = rcChange;
        rcChange = 0;  // Zero the change counter
        rcT[0] = rcTimes[0];
        rcT[1] = rcTimes[1];
        rcT[2] = rcTimes[2];
        rcT[3] = rcTimes[3];
        sei();   // reenable interrupts

        Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
        << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
      }
      sei();   // reenable interrupts
    }

Note, for the above you may need to download and install `Streaming.h` via [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/).

**Rotary encoder quadrature-counting**

The program above tracks and reports pulse-length times, instead of decoding the quadrature signals the rotary encoder provides.  The program below reports rotary encoder counts, but does so using INT0 and INT1 instead of PCIs.  You will want to combine relevant portions of the two routines together – ie, use the interrupt setup and handling framework from above, with the body of the service routine from below.  [Note, this program is from my [answer to previous question #16420](https://arduino.stackexchange.com/a/16420/3917).  The encoder decoding code within it is faster and shorter than other decoding code I've looked at, and is fast enough to support two encoders rotating simultaneously while losing few counts.]

<!-- language: lang-c -->

    /*  roto_jw4.ino -- JW, 29 September 2015 --
     *  A 4-state state-machine implementation of rotary
     *  encoding for KY-040 rotary knobs.  The state-machine picture at
     *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
     *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
     *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
     *  decreasing on transitions the other way.  Transitions between 00
     *  and 11 or 10 and 01 are invalid.  This code detects valid
     *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
     *  up-count events by the tri-bit value ABA' (where A' is the new
     *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
     *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
     *  (a bit mask of 0x99).
     *
     *  On a KY-040 unit I tested, there are 30 detent positions per turn.
     *  With this unit the code generates 60 counts per turn, which can be
     *  seen individually as one turns the rotor slowly.  Odd counts
     *  appear between detents, even counts at detents.
     *
     *  Set quadrature-signal pin numbers, via PinA and PinB constants.
     *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
     *  on encoder AB pins, else set IPINMODE to INPUT
     */
    enum { PinA=2, PinB=3, IPINMODE=INPUT };

    static  byte abOld;  // Initialize state
    volatile int count;  // current rotary count
             int old_count;  // old rotary count

    void setup() {
      pinMode(PinA, IPINMODE);
      pinMode(PinB, IPINMODE);
      attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
      attachInterrupt(1, pinChangeISR, CHANGE);
      abOld = count = old_count = 0;
      Serial.begin(115200);
      Serial.println("Starting Rotary Encoder Test");
    }

    // On interrupt, read input pins, compute new state, and adjust count
    void pinChangeISR() {
      enum { upMask = 0x66, downMask = 0x99 };
      byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
      byte criterion = abNew^abOld;
      if (criterion==1 || criterion==2) {
        if (upMask & (1 << (2*abOld + abNew/2)))
          count++;
        else count--;  // upMask = ~downMask
      }
      abOld = abNew;  // Save new state
    }

    void loop() {
      if (old_count != count) {
        Serial.print(millis());
        Serial.print("  ");
        Serial.println(count);
        old_count = count;
      }
    }

**Using other pins for PCIs**

If you wish to monitor two rotary encoder lines using pin change interrupts on pins other than A0 and A1, you *may* need to replace vector `PCINT1_vect` with some other vector, and *will* need to replace the pins mask with a different one.  The following program can be used to display a table of PCI vectors, masks, etc.  (As noted in my question [Why PJ0 and PJ1 are not reporting as PCINT pins](https://arduino.stackexchange.com/q/16551), pins PJ0 and PJ1 on an ATmega-2560 board will not report correctly.)

<!-- language: lang-c -->

    /*  pinsList -- JW, 4 October 2015 --
     *
     *  Displays a list of Arduino pin numbers for current kind of Arduino
     *  board, along with port codes, pin-change-interrupt numbers, and
     *  pin-change-interrupt vector numbers.
     *
     *  Here are two examples of output lines for pin 11, the first for an
     *  Uno, the second for a Mega:
     *
     *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
     *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
     */
    //-----------------------------------------------------------
    // Given a value with 1 bit set, return bit #.  Else return 9.
    byte getBitfromBV (byte m) {
      byte b=0, v=1;
      while (v) {
        if (m==v)
          return b;
        ++b; v <<= 1;
      }
      return 9;
    }
    //-----------------------------------------------------------
    void processPinNumber(byte pin) {
      char buffi[128];  // We create text-to-write in buffi
      byte nbuff=0;   // #chars used in buffi
      byte nPCICR;   // 0, 1, or 2 for mask-register #
      byte bitInByte;  // 0 to 7 for bit in I/O mask
      byte pinPort;   // pin's port #, in range 1 to 12
      byte PCInum;   // PCINT# if pin is a PCI pin
      char *portLet = "?ABCDEFGHIJKL";

      if (pin >= NUM_DIGITAL_PINS) return;

      pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
      bitInByte = getBitfromBV(digitalPinToBitMask(pin));

      nbuff = snprintf(buffi, sizeof(buffi), "  -   P%c%d  0xx",
         pin, portLet[pinPort], bitInByte, 1<<bitInByte);

      // Indicate if it's a PWM pin
      if (digitalPinHasPWM(pin)) {
        nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
      } else {
        nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
      }

      // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
      if (digitalPinToPCICR(pin)) {   // Is it a PCint pin?
        nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
        PCInum = nPCICR*8 + bitInByte;
        nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
           "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
      }
      Serial.println(buffi);
    }
    void setup() {
      delay(50);
      Serial.begin(115200);
      delay(50);
      while (!Serial) ;             // wait for serial stream to connect
      Serial.println("\nPin#  Port  Mask  PWM   PCINT");
      for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
        processPinNumber(p);
      Serial.end();
    }

    void loop() {
    }

**ISR-framework-generating Sketch**

The program below generates frameworks for specified PCI pins and prints them to `Serial`.  See usage comments within the program.  This provides an easy way to create the basic outline of an ISR to handle PCIs.

<!-- language: lang-c -->

    /*  pinFunctions -- JW, 1 October 2015 --
     *
     *  Displays direct pin-access and pin-change-interrupt setup code,
     *  for inclusion in a sketch, for specified pin numbers.  The
     *  displayed code can be pasted into a sketch where execution speed
     *  matters.
     *
     *  When called with a call like `genCode ("affix", "9,11");`, genCode
     *  will produce a set of procedures: ISR routines for pins that
     *  support pin-change interrupts; get and put routines to read from
     *  or store to registers; and a setup routine.  The generated get,
     *  put, and setup routines will have names formed by suffixing the
     *  affix to get, put, and setup, respectively.  For example, if the
     *  affix is ML47 the names of generated routines will include
     *  getML47, putML47, and setupML47.
     *
     *  Generated get() and put() code is of the following forms (in which
     *  u, v are port-letters; values mu, mv, ni are numerical constants;
     *  and w is a parameter value) if all the pins, n1, ... nk in the
     *  pins-list are in port u, under mask mu:
     *
     *             return PINu & 0xmu; // Get pins n1, ... nk
     *             PORTu = PINu & ~mu | w & mu;
     *
     * For example, with Uno pins 3, 4, 6, get() and put() bodies are:
     *
     *             return PIND & 0x58;
     *             PORTD = PIND & 0xa7 | w & 0x58;
     *
     *  The following forms arise if the pins are in ports u and v; and so
     *  forth if more than two ports are involved.
     *
     *             return PINu & masku | PINv & mv; // Get pins n1, ... nk
     *             PORTu = w & 0xmu;   // Put pins <u pins>
     *             PORTv = w & 0xmv;   // Put pins <v pins>
     *
     *  genCode() does not require that all pins belong to the same port.
     *  It will produce usually-desired results if bit positions don't
     *  interfere, otherwise may not.  For example: An Arduino Uno
     *  pins-list "2,10" corresponds to port pins PD2 and PB2.  Both are
     *  in bit position 2, so get's result will be the OR of the PB2 and
     *  PD2 values, while put will store the same bit value to both pins.
     *
     *  To use the pasted code: A statement like `w = getAFFIX();` will
     *  read a set of pins and store the value in w.  A statement like
     *  `putAFFIX(w);` will write w to a set of pins.  Also, add a line
     *  like the following in setup():
     *
     *       setupAFFIX(ioMode, enablePCI);
     *
     *  In the `setupAFFIX(ioMode, enablePCI);` call, substitute an
     *  appropriate affix in place of AFFIX; substitute one of INPUT,
     *  OUTPUT, or INPUT_PULLUP in place of ioMode; and substitute 1 or 0
     *  for enablePCI, to enable or not enable pin-change-interrupt setup.
     *
     *  If you want to save room and don't plan to use pin-change
     *  interrupts, instead of merely not enabling PCI setup, you can
     *  remove the ISR routines and the `if (enablePCI) {...}` section
     *  from the pasted code.
     *
     *  Each generated ISR routines contains one line, of form
     *
     *        byte datum = PINu & mu; // Read pins <list>
     *
     *  The idea is that you will paste the generated ISR into your
     *  sketch, then populate it with appropriate interrupt processing
     *  code.  Note 1: datum contains data from one port, a port which
     *  belongs to the interrupt vector.  If you need data from other
     *  ports as well, then paste appropriate lines from the get() routine
     *  into the ISR.  Note 2: This version of pinFunctions does not
     *  announce pins that don't belong to PCI vectors, if any.
     *  (Processor pins with functions like PCINT0 ... PCINT23 belong to
     *  PCI vectors.)  You can compare the masks used in get() to those
     *  used in the ISR's to detect this.  If the masks differ, some pins
     *  aren't PCI pins.  Note 3: If multiple ports' pins belong to one
     *  vector (eg Ard#0 or PE0 for PCINT8 and Ard#15 or PJ0 for PCINT9,
     *  both on vector PCINT1_vect), a code-generation error of form "Pin
     *  x's port #y isn't #z" will appear and you will need to paste in
     *  appropriate lines from get() or otherwise manually prepare correct
     *  code.
     */

    char buffi[128];  // We create text-to-write in buffi
    char buffn[32];   // also in buffn
    byte nbuff=0;   // #chars used in buffn
    char *c;   // c points into pinsList
    byte pin;   // pin number
    byte nPCICR;   // 0, 1, or 2 for mask-register #
    byte vecmask;   // OR of 1<<nPCICR values
    byte intmask[3];  // OR of int. enable masks
    byte maskBitPC;   // 0 to 7 for bit in PCI mask
    byte maskBitIO;   // 0 to 7 for bit in I/O mask
    byte pinPort;   // pin's port #, in range 1 to 12
    byte PCInum;   // PCINT# if pin is a PCI pin

    // Given a value with 1 bit set, return bit #.  Else return 9.
    byte getBitfromBV (byte m) {
      byte b=0, v=1;
      while (v) {
        if (m==v)
          return b;
        ++b; v <<= 1;
      }
      return 9;
    }

    // Get next pin number from pinsList, and its associated reg numbers
    byte getPinNumber() {
      byte cc=*c;
      if (!cc)
        return 0;
      pin=0;
      for (; '0' <= cc && '9' >= cc; cc=*++c) {
        pin = 10*pin + cc - '0';
      }
      pinPort = maskBitIO = PCInum = nPCICR = maskBitPC = 0;
      if (pin < NUM_DIGITAL_PINS) {
        pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
        maskBitIO = digitalPinToBitMask(pin);
        if (digitalPinToPCICR(pin)) {   // Is it a PCint pin?
          nPCICR  = digitalPinToPCICRbit(pin); // 0, 1, 2 for p's PCICR bit#
          maskBitPC = digitalPinToPCMSKbit(pin);
          PCInum =  nPCICR*8+ getBitfromBV(maskBitIO);
        }
      }
      if (!cc)     // At end of string? If so,
        --c;     // allow for caller incrementing c
      return 1;
    }

    void genCode (char *affix, char *pinsList) {
      char *portLet = "?ABCDEFGHIJKL?";
      enum { portMax=12 };
      byte readmask;  // Input-bits mask
      byte port;   // Port #

      snprintf(buffi, sizeof(buffi), "\n// %s : pins %s", affix, pinsList);
      Serial.println(buffi);

      //==================================================================
      // Generate  "byte get<affix>() { // Get pins <list>"
      //              return PINu & mu | PINv & mv | ...
      //            }"
      nbuff = snprintf(buffi, sizeof(buffi), "byte get%s () { // Get pins", affix);
      for (port=1; port<=portMax; ++port) {
        for (readmask=0, c = pinsList; getPinNumber(); ++c) {
          if (pinPort==port) {
     nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
     readmask |= maskBitIO;
          }
        }
        if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
      }
      Serial.println(buffi); // Print first line of get...() function
      nbuff = snprintf(buffi, sizeof(buffi), "  return");
      for (port=1; port<=portMax; ++port) {
        for (readmask=0, c = pinsList; getPinNumber(); ++c) {
          if (pinPort==port) {
     readmask |= maskBitIO;
          }
        }
        if (readmask)
          nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, " PIN%c & 0xx |",
       portLet[port], readmask);
      }
      snprintf(buffi+nbuff-2, sizeof(buffi)-nbuff, ";\n}"); // -2 loses extra " |"
      Serial.println(buffi);  // Print last two lines of get...() function

      //==================================================================
      // Generate  "void put<affix>(byte w) { // Put pins <list>"
      //              PORTu = PINu & ~mu | w & mu;
      //              ...
      //            }"
      nbuff = snprintf(buffi, sizeof(buffi), "void put%s () { // Put pins", affix);
      for (port=1; port<=portMax; ++port) {
        for (readmask=0, c = pinsList; getPinNumber(); ++c) {
          if (pinPort==port) {
     nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
     readmask |= maskBitIO;
          }
        }
        if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
      }
      Serial.println(buffi); // Print first line of put...() function
      for (port=1; port<=portMax; ++port) {
        for (readmask=0, c = pinsList; getPinNumber(); ++c) {
          if (pinPort==port) {
     readmask |= maskBitIO;
          }
        }
        if (readmask) {
          snprintf(buffi, sizeof(buffi), "  PORT%c = PIN%c & 0xx | w & 0xx;",
            portLet[port], portLet[port], (byte)(~readmask), readmask);
          Serial.println(buffi);  // Print a port-setting line of put...() function
        }
      }
      Serial.println("}");  // Print last line of put...() function

      //=================================================================
      // Generate ISR's:  Process 3 possible pin-change interrupt vectors
      vecmask = 0;
      for (byte ivect=0; ivect < 3; ++ivect) {
        byte sinPort=15;  // currently-in-use same port #
        intmask[ivect] = 0;
        byte busyvect=0;        // Assume vector not used
        byte readmask=0;        // Input mask
        // Loop to see if vector is used
        for (c = pinsList; getPinNumber(); ++c) {
          if (nPCICR == ivect) {
     ++busyvect; sinPort = pinPort; // Bits on same port get read once
     vecmask |= 1<<ivect;
     intmask[ivect] |= 1<<maskBitPC;
          }
        }
        if (busyvect) {  // If vector is busy, create its ISR
          snprintf(buffi, sizeof(buffi), "ISR(PCINT%d_vect) {", ivect);
          Serial.println(buffi);
          nbuff = 0;
          for (c = pinsList; getPinNumber(); ++c) {
            // See if it's a PCint pin, and on the current vector
     if (digitalPinToPCICR(pin) && nPCICR == ivect) {
       intmask[ivect] |= 1<<maskBitPC;
       readmask |= digitalPinToBitMask(pin);
       nbuff += snprintf(buffn+nbuff, sizeof(buffn)-nbuff, " %d,", pin);
       if (pinPort != sinPort) {
         snprintf(buffi, sizeof(buffi), "Pin %d's port #%d isn't #%d",
           pin, pinPort, sinPort);
         Serial.println(buffi);
       }
     }
          }
          snprintf(buffi, sizeof(buffi), "  byte datum = PIN%c & 0xx; // Read pins %s\n}",
            portLet[sinPort], readmask, buffn);
          Serial.println(buffi);
        }
      }
      snprintf(buffi, sizeof(buffi), "void setup%s(byte ioMode, byte enablePCI) {", affix);
      Serial.println(buffi);
      for (c = pinsList; getPinNumber(); ++c) {
        nbuff = snprintf(buffi, sizeof(buffi), "  pinMode(-, ioMode); // -, P%c%d",
          pin, pin, portLet[pinPort], getBitfromBV(maskBitIO));

        if (maskBitPC)
          snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "   PCINT %d", PCInum);
        Serial.println(buffi);
      }
      Serial.println("  if (enablePCI) {");
      for (byte ivect=0; ivect < 3; ++ivect) {
        if (intmask[ivect]) {
          snprintf(buffi, sizeof(buffi), "    PCMSK%d |= 0xx;", ivect, intmask[ivect]);
          Serial.println(buffi);
        }
      }

      snprintf(buffi, sizeof(buffi), "    PCIFR  |= 0xx; // clear PC interrupts if any",
        vecmask);
      Serial.println(buffi);
      snprintf(buffi, sizeof(buffi), "    PCICR  |= 0xx; // enable PC interrupts\n  }\n}",
        vecmask);
      Serial.println(buffi);
    }

    void setup() {
      Serial.begin(115200);
      while (!Serial) ;             // wait for serial stream to connect
      Serial.println("Starting Code Generation");
      genCode ("A0A1",  "14,15\0"); // A0, A1 on a nano
      genCode ("Pair78",  "7,8");
      genCode ("Trip346",  "3,4,6");
      genCode ("Quad789A", "7,8,9,10");
      genCode ("Hex8toD",  "8,9,10,12,11,13");
      genCode ("LotsSmall", "2,6,7,8,9,10,11,12,13,14,15,19,20,21,22,28,29,30,31,37");
      genCode ("LotsBig",   "31,37,38,37,38,45,46,52,53,54,55,61,62,63,69,70,71,76");
      Serial.println("Ending Code Generation");
      Serial.end();
    }

    void loop() {
    }


message:
How to have precise measurements

I need to display measurements of a sensor which need to be presented on a precise time-scale.
Since the loop function is not quite precise, how can i make sure that i can measure at say for example exactly 1ms?
( I am using an ADXL345 sensor )
Thanks a lot!

body:
Microcontrollers have built in peripherals called Timers. They are used for many purposes, including working out when something should be done.

There are plenty of good Timer libraries around for the Arduino, including the popular [TimerOne/TimerThree libraries](http://playground.arduino.cc/Code/Timer1).


body:
The [ADXL345][1] has both a FIFO and data rate setting. This allows sampling to be done with a precise frequency without having to use timers, etc, on the MCU. The MCU/Arduino has to fetch data before the FIFO overflows. The max sampling frequency depends on the communication protocol (I2C or SPI), i.e. how fast the MCU can empty the FIFO.

It is possible to use the ADXL345 in stream mode, collect samples at a fixed rate, and get an interrupt when the FIFO has been filled to a specified level (watermark). The samples can then be read in burst mode.

The samples will be on a "precise time-scale".

There are even more advanced usages of the device with tap, double-tap and free fall detect.

Please see Data Rate setting and FIFO control in datasheet.

Cheers!

PS: Using I2C at 100 KHz will take 1 ms just to address the device. Addressing a register will take another ms and a ms per data byte. Reading the data register (six bytes) will take at least 8 ms. Realistic max sample rate with I2C at 100 KHz is 10-100 Hz. There is also limited amount of memory for buffers.

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf


message:
Why is 1020 steps used for crossfading colors on an RGB LED?

I'm looking into how to smoothly crossfade between colors on an RGB LED with the Arduino and I've found this piece of code for doing it:
https://www.arduino.cc/en/Tutorial/ColorCrossfader

I understand all parts of the code except for one thing.
The values for red, green and blue are changed incrementally through 1020 steps, because 255*4 = 1020.
But WHY 4? There are 3 colors, and 255 * 3 = 765. So why not 765 steps?

body:
Extract from code:

    int wait = 10;      // 10ms internal crossFade delay; increase for slower fades

    for (int i = 0; i <= 1020; i++) {
      redVal = calculateVal(stepR, redVal, i);
      grnVal = calculateVal(stepG, grnVal, i);
      bluVal = calculateVal(stepB, bluVal, i);

      analogWrite(redPin, redVal);   // Write current values to LED pins
      analogWrite(grnPin, grnVal);
      analogWrite(bluPin, bluVal);

      delay(wait); // Pause for 'wait' milliseconds before resuming the loop

      if (DEBUG) { // If we want serial output, print it at the
        if (i == 0 or i % loopCount == 0) { // beginning, and every loopCount times
        }
        DEBUG += 1;
      }
    }

The 1020 in the loop determines the time taken to make the crossfade from the current colour to the next - not the total cycle as you seem to think. In the main loop we have

    crossFade(red);
    crossFade(green);
    crossFade(blue);
    crossFade(yellow);

And each of these crossfades will take 1024 * wait ms to complete. 'wait' is set to 10 ms so I would expect it to take 10.24 s to complete a fade from one colour to the next.

[Edit]

I think the large number (1020) is just to give a fine resolution in the steps calculation which is all done with integers. (What struck me as odd is that it doesn't use 256 * 4 = 1024.) The larger we make this number the finer the step resolution becomes. With coarse steps the ramp will complete too early.

Let's say we had 255 steps and we wish to go from 134 to 0.

    step = 255 / (endValue - prevValue)
    step = 255 / (134 - 0 ) = 1.9 which will be rounded down to 1.

This means that the crossfade will be complete in 134 steps instead of 255. i.e., it will finish 47% early.

If we use 1020 steps and we wish to go from 134 to 0.

    step = 1020 / (endValue - prevValue)
    step = 1020 / (134 - 0 ) = 7.6 which will be rounded down to 7.

This means that the crossfade will be complete in 938 steps instead of 1020. i.e., it will finish 8% early.


body:
For my transition between colors I used arrays during the setup to collect the main transitions (bigger jumps between RGB values) then during the loop I used a series of `analogWrite()` commands essentially splitting the jumps by a 16th, for example starting at `255, 0, 0` the next array value was `223, 0, 0` in the loop it went from `255, 0, 0` to `253, 0, 0` to `251, 0, 0` finally landing the last loop value of `225, 0, 0` before starting the loop over at the next array value of `223, 0, 0`. It's important to realize what colors transition into others and what the corresponding RGB values are of that transition.

Tomorrow I'll post my code, it's a bit messy as it was more proof of concept that starting with a distinct plan.


message:
AVR - How to know that there is collision between stack and heap or the memory has filled?

I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

body:
In simple terms: if the stack and heap have collided then the program will most likely crash, and any countermeasures you may have in place are now null and void.

However, you can find out the current amount of free memory quite easily by looking at where the top of the heap is and creating a local variable on the stack and getting its address - subtract one from the other and you get the free memory size.

That's exactly what the [MemoryFree Library](http://playground.arduino.cc/Code/AvailableMemory) does for you.


body:
> I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

The first thing that happens is that malloc() will return NULL saying that memory could not be allocated. The [AVR heap implementation][1] has a few safety measures. One is to check that there is a minimum margin (__malloc_margin) between end of the heap and the top of the stack. This can be adjusted by the application.

[![Heap-Stack][2]][2]

Typically the minimum margin should be able to hold [the largest stack usage][3] (typically deepest function call tree with the largest local variables usage) plus largest ISR stack usage.

If the stack runs into the heap the memory block/s at the end of the heap is/are corrupted. What happens depends on the type of data structure.

Not checking NULL return from malloc() gives some interesting errors on the AVR as the [processors registers][4] are memory mapped. NULL points to R0.

[![AVR Memory Map][5]][5]

A good rule of thumb when using malloc() in small scale embedded systems is 1) avoid it, 2) allocate memory with malloc() during the setup(). All other dynamic memory need be allocated temporary on stack and only for the processing.

  [1]: http://www.nongnu.org/avr-libc/user-manual/malloc.html
  [2]: https://i.stack.imgur.com/Lc5uw.png
  [3]: http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_ramoverlap
  [4]: https://gcc.gnu.org/wiki/avr-gcc#Register_Layout
  [5]: https://i.stack.imgur.com/RxwSL.jpg


message:
What is the proper way to turn an Arduino UNO into an ISP?

I have a bricked Arduino Uno and I want to try to flash the bootloader. I'm trying to figure out how to do it. [On this tutorial from SparkFun](https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader) you can see this diagram:

[![Spark Fun layout][1]][1]

They also show this table of the pinout

[![SparkFun Pinout][2]][2]

That seems simple enough but it's totally different than the official tutorial, ["Circuit (targeting Arduino Uno, Duemilanove, or Diecimila)"](https://www.arduino.cc/en/Tutorial/ArduinoISP)

[![Schematic between two Arduinos][3]][3]

Which also says

> An Arduino board serving as an ISP to program the ATmega on another Arduino board. On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (after uploading the ArduinoISP sketch). Note that you need access to the reset pin on the target board, which isn't available on NG or older boards.

So do I need a 10 uF capacitor between reset and ground? How do I put a 10 uF capacitor in between reset and ground when, in this configuration, reset is connected to PIN 10? Why are there two configurations? What's the upsides and downsides to either of them?

  [1]: https://i.stack.imgur.com/qad6g.jpg
  [2]: https://i.stack.imgur.com/TL2O2.png
  [3]: https://i.stack.imgur.com/qv3la.png

body:
The wiring is actually identical. It just uses the ISP header (2x3 pins) on the target board, instead of the pins 5v, GND, RST, 11, 12, 13. Just like the table you added says.

The downside to using the ISP header, is you need a male to female wire for connecting. Upside is you can easily take of these 6 pins, and connect it to a different arduino to be programmed.

I always needed to add a capacitor between RESET and GND. The exact value isn't that critical.

The reset pin is the one to the left of 3v3.


body:
Take a look at my circuit for a minimal "Arduino":

[![Minimal circuit][1]][1]

The top image in the question uses the ICSP header, which you can see from the schematic "mirrors" pins on the processor. That is:

* SCK is D13
* MISO is D12
* MOSI is D11
* Reset on the target goes to D10 on the programming board
* Vcc and Gnd are connected

Trace out the wires to the ICSP header and you will see.

---

> So do I need a 10 uF capacitor between reset and ground?

No you do not.

---

>  I have a bricked Arduino Uno and I want to try to flash the bootloader.

See my page about [programming a bootloader](http://www.gammon.com.au/bootloader).

---

> Why are there two configurations?

Just different ways of connecting the same thing to the same thing.

---

> What's the upsides and downsides to either of them?

No difference.

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


message:
What's the difference between ICSP vs ISP?

I'm not sure if these terms are interchangeable or not. What's the difference between ICSP and ISP? Is it simply the reset? I've shown [two configurations in this question I just asked](https://arduino.stackexchange.com/questions/19129/what-is-the-proper-way-to-turn-an-into-an-isp). Are they both ICSP?

body:
The difference between ISP and ICSP is a hyphen.

ISP stands for In-circuit Serial Programming, and ICSP stands for In Circuit Serial Programming.

Any arrangement that allows you to program a microcontroller while it is in a circuit using a serial protocol can be called ISP or ICSP.


body:
According to the Atmega32U4 datasheet:

> The device is manufactured using ATMEL’s high-density nonvolatile memory technology. The On-chip ISP Flash allows the program memory to be reprogrammed in-system through an SPI serial interface, by a conventional nonvolatile memory programmer, or by an On-chip Boot program running on the AVR core.

I can't find the word "ICSP" in the datasheet. The quoted paragraph doesn't really explain the acronym. It could be an anagram of SPI. ;)

---

It seems clear to me that "in system" and "in circuit" are referring to the same thing. The program is serial rather than parallel as it uses SPI (Serial Peripheral Interface).

---

> I've shown two configurations in this question I just asked. Are they both ICSP?

Not really two configurations, because the ICSP header on the board is directly connected to the pins you showed in the other configuration. You may as well talk about using different ground pins as a "different configuration".


message:
Does Arduino.cc silkscreen the pin headers? What explains the differences here?

I have two Arduino's. One from .org, and one from .cc. The arduino.org one has really nice silk screening on the header pins. The arduino.cc one does not. In addition there are some visible component differences. One has a 504S (not sure what this chip is), one has a 504L. The button on the .org one is a bit more tactile. The headers on the top (not the ICSP) headers are missing on the .org one. And, the four points that look like they're for soldering or testing are absent. I can try to get a high-res picture of the two up.

I bought the .org one in a beginner kit online from Amazon (from the official seller). And, the .cc I bought from their website directly.

The .org one seems like it's made from higher-end components, and actually having the headers at the top makes it seem more polished. Is there any through guide to what these differences are or a changelog from one hardware revision to another?

body:
No, there is nothing that documents the differences as in a changelog, purely because this is not an iterative change.

The two boards are designed and manufactured by two different (competing) companies in two different countries (USA and Italy) using different component suppliers.

Just because they both say Arduino UNO doesn't make them both the same board - not these days anyway, since the founders of Arduino got really childish and started throwing their faeces at each other like monkeys in the zoo.


message:
How to build circuit to switch to other power source if primary source dies?

I would like to have a backup battery connected to a device that requires an uninterrupted power supply, like an Arduino or Raspberry Pi, so that if my primary power source (USB plug) gets pulled, the device will switch to being powered by the battery.

I need a solution that I can either build on a breadboard or buy for only a couple dollars. Does anyone know a solution? I'm assuming this is a common need and think I perhaps am not searching with the correct key words.

Edit:

I would like to add that I may also use 4AA batteries and a DC-DC step down module to produce 5V exactly to power a 5V device, so I'm looking for a solution that accepts 5V. Assume the device, let's say Raspberry Pi, takes 5V, the power supply is 5V, and the battery backup is 5V.

body:
Your $2 budget rules out some of the more-effective possible solutions, such as using an actual UPS (uninterruptible power supply) system.

One affordable approach is to connect the plus side of a 3.7 V lithium-polymer battery through a Schottky diode [such as MBR0520, SS14, 1N5819] to the +5 V line of an Arduino board.  (I haven't looked at Raspberry Pi schematics and don't know if this will apply there.)  Hook the minus side of the battery to Arduino ground.

Ideally, the battery voltage less the voltage drop through the diode (say .4–.5 V) should be just less than the voltage that USB supplies.  Ie, just under 5 V if you have a 5 V board, or just under 3.3 V for a 3.3 V board.  Note, most 3.3 V Arduino systems are specified to run at 8 MHz rather than 16.  There's a good chance a 5 V Arduino running at 16 MHz would continue to run ok when powered by about 3.3 V, but it's out of spec.

If your battery voltage exceeds 5 V you won't be able to make the connection quite so directly.  Besides certain risks of damage (see eg Method #5 and Method #8 of [10 Ways to Destroy An Arduino](http://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/)) there will be the practical matter that the higher battery voltage will cause its power to be used preferentially to the USB power, thus discharging the battery so that it won't act as a backup.

*Edit:* The question-edit says the system uses 5 V, and seems to suggest the primary 5V power supply uses 4 AA batteries and a DCDC converter.

If the DCDC converter is a step-down [buck converter](https://en.wikipedia.org/wiki/Buck_converter) it will go out of regulation when the input voltage from the four AA's goes below 5 V, which is 1.25 V per cell.

As you can see from the following graph, if the discharge rate of a typical alkaline cell is 100 mA, it still has about half its power left when its voltage goes below 1.25 V.  To fully use up the alkaline batteries, you could use a [buck-boost converter](https://en.wikipedia.org/wiki/Buck–boost_converter) or could test if your buck converter just passes the voltage on through, as opposed to shutting down when the input voltage is low.

[![alkaline AA-battery discharge curve][1]][1]

(Note, the AA-battery discharge curves shown above and below are from the [powerstream.com's “AA tests”  web page](http://www.powerstream.com/AA-tests.htm).)

For the backup battery, where you also want 5 V output, an economical possibility is use of four AA NiMH cells, with nominal voltage 1.2 V per cell. However, initial voltage officially can exceed 1.4 V per cell, giving 5.6 V total:

[![NiMH AA-battery discharge curve][2]][2]

A Schottky diode in series will bring that down to say 5.2 V, an acceptable level for powering a 5 V system.  But if the primary supplies 5.0 V, the backup will end up discharging slightly until its output voltage goes below that of the primary.  If that's acceptable, fine.  Otherwise, you could use a diode like 1N4001, with 0.7 to 0.8 volts of drop at 0 to 150 mA output.  Instead of losing some backup power at first (due to higher backup than primary voltage) you will lose some at the end, due to backup voltage going too low slightly sooner. That won't be a problem, however, if you restore the primary supply and recharge the backups in time to prevent over-discharge damage to the backup batteries.

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


message:
RF24 tranceivers: trouble with two way communication

I am using RF24 modules with my two Arduinos Leonardo with the [RF24][1] library. My goal is to be able to press a button on the first Arduino which will light up an LED on the second Arduino, and be able to press a button on the second Arduino to light up an LED on the first Arduino. I was easily able to figure this out as a one-way transmission with the first Arduino only transmitting and the second only receiving, but I am unable to make it a two-way transmission, where each Arduino can transmit and receive at the same time.

This is my code so far:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #include <RF24_config.h>

    int msg[1];
    RF24 radio(9,10);
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    const uint64_t pipe2 = 0xF0F0F0F0AA;
    void setup(void){
      Serial.begin(57600);
      pinMode(A0, INPUT);
      radio.begin();
      radio.openWritingPipe(pipe);
      radio.openReadingPipe(1,pipe2);
    }

    void loop(void){
      int charToSend[1];
      charToSend[0] = digitalRead(A0);
      if (!radio.write(charToSend,1)) {Serial.println('didn\'t send');}
      radio.startListening();
      if (radio.available()){
        bool done = false;
        done = radio.read(msg, 1);
        Serial.println(msg[0]);
        digitalWrite(13, msg[0]);
      }
      radio.stopListening();
      radio.powerDown();
      delay(10);
      radio.powerUp();
    }

But the `radio.write()` is returning false and therefore not sending.

  [1]: https://github.com/maniacbug/RF24

body:
The main thing that I can see wrong with your sketch is that the logic of your methodology is backwards.

You are spending most of your time either with the radio asleep, or not in listening mode, so it can not receive anything.

Instead you need to spend all your time in listening mode waiting for messages to arrive, and only when the button changes state do you want to switch off listening mode and send a packet to the other end. As soon as you have done that you then go back to listening.

You can't listen while the radio is powered down, so using `powerDown()` and `powerUp()` is just nonsense.


message:
Arduino ultrasonic distance meter doesn't display correct distance

The Arduino distance meter that I made doesn't display the correct distance. It just displays "0.0 inches".

Here's the code I used:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int pingPin = 7;
    int inPin = 6;
    long duration, inches, cm;
    int indec, cmdec;
    int inchconv = 147;
    int cmconv = 59;
    String s1, s2;

    void setup() {
      lcd.begin(16, 2);
      pinMode(pingPin, OUTPUT);
      pinMode(inPin, INPUT);
    }

    void loop()
    {
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(pingPin, LOW);

      duration = pulseIn(inPin, HIGH);

      inches = microsecondsToInches(duration);
      indec = (duration - inches * inchconv) * 10 / inchconv;
      cm = microsecondsToCentimeters(duration);
      cmdec = (duration - cm * cmconv) * 10 / cmconv;
      s1 = String(inches) + "." + String(indec) + "in" + "     ";
      s2 = String(cm) + "." + String(cmdec) + "cm" + "     ";
      lcd.setCursor(0, 0);
      lcd.print(s1);
      lcd.setCursor(0,1);
      lcd.print(s2);

      delay(100);
    }

    long microsecondsToInches(long microseconds)
    {
      return microseconds / inchconv;
    }

    long microsecondsToCentimeters(long microseconds)
    {
      return microseconds / cmconv;
    }

Here's the wiring diagram:

[![Fritzing diagram of Arduino distance meter][1]][1]

Might there be a problem in my code, or in my wiring?

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

body:
To solve a problem like this you need to break it down into smaller pieces so that you can build up some confidence about what is working and what is not. When you share a problem like this as a question it helps if you can give us some idea of your experience level and of what you've already done to debug the problem – that helps with avoiding telling you what you already know and makes it easier to focus in on where the problem might be.

From what you've said it appears that you have things working well enough that you get a display on the LCD but it does not represent a meaningful distance.

Looking at your schematic the first thing that comes to my mind is that you have the ultrasonic sensor at the opposite end of the breadboard from the LCD. Many breadboards split their power rails at the middle. So start by confirming that you have power to the sensor.

After that, double-check the rest of your wiring.

The next step for me would be to confirm that I understood the sensor and to try and prove that it was working as I expected. Look for some sample code that is known to work (often the site you bought the sensor from will have links to beginning tutorials or code samples). Try that to see if the sensor works with the sample code.

If that doesn't work then check to see what you can do to prove the sensor is good (or bad). You might also contact the vendor to see if they can give you advice on proving that the sensor works.

Basically, break the problem down into "bite sized" chunks and work through it one step at a time, doing the simple stuff first. Try not to assume anything…


body:
Maybe you should use the New Ping library and check if the sensor works without LCD:

https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home


message:
Programming a USB mouse connected to the Intel Edison Arduino expansion board

How can I programme a USB mouse connected to the standard USB port of the Intel Edison's Arduino expansion board?  I would like to measure the displacement of the mouse and also specify the frequency of image capture using the mouse's optical sensor.  I do not know much about programming so tutorials relating to my project would be very helpful.

Thanks

body:
Here's a simple introduction to using the USB mouse as an input device. That might be a good starting point.

http://tahmidmc.blogspot.com/2015/12/using-input-device-on-embedded-linux.html


message:
I2C LCD displaying weird characters

I have connected an LCD with an I2C backpack to my Arduino Uno but it prints the wrong characters. The weird thing is that it worked fine for a while and when I updated the code (but didn't change anything to do with the LCD) it started displaying the wrong characters. This happened earlier today too. That time, reinstalling the LiquidCrystal library worked, but it doesn't now.

Does anyone know what might be the problem so I can fix it permanently?

The LCD's SDA and SCL are connected to A4 and A5 respectively and I'm running this code:

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

    LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16     chars and 2 line display

    void setup()
    {
      lcd.init();
      lcd.backlight();
      lcd.setCursor(0,0);
      lcd.print("Hello, world!");
    }

    void loop()
    {
        }

and this is what's displayed on the screen:

[![some random characters][1]][1]

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

body:
If you look up the ASCII codes for what you sent vs what was displayed, and also look at "Table 4 Correspondence between Character Codes and Character Patterns (ROM Code: A00)" in an HD44780U spec sheet, you will find hexadecimal values like the following.

- e 65, V  56
- l 6C, ニ C6
- o 6F, θ  F2
- o 6F, π  F7
- r 72, &  26
- d 64, B  24
- and so forth.

It appears that the high nibble of what you sent is being used as the low nibble of what is displayed, and the low nibble is being used as the high, but with some bits sometimes going wrong.  Note, a space is 0x20, and the reverse of that is 0x02, which would access a character from the character-generator RAM, which will contain random bits and produce a random blob as in your picture.

If your mis-specification of display size (20, 4 vs 16, 2) isn't responsible for the problem, then maybe there is a hardware problem with the backpack you've soldered on to the LCD.  Look at it under a bright light, using a binocular parts-examination microscope if you've got one, and see if there are loose solder particles, extra solder flux, or loose solder connections on that board.  If you have an oscilloscope, check if your I2C signals are clean and have full swing.


body:
From what I can see, it seems, in this line:

        LiquidCrystal_I2C lcd(0x27,20,4);

wrong parameters have been passed to the constructor. The last two arguments are supposed to indicate the number of columns and rows on the screen. Your screen has 16 columns and 2 rows, whereas you passed 20 columns and 4 rows to the constructor. This could be the problem.


body:
I experienced this while using a STM32f429 discovery board,  and I found out there are two reasons that this happens.

 1.  when using a fast microcontroller (180 MHz clock),  if you send I2C packet consecutive LCD may not be that fast to understand it and as James said in other post LCD may lose some packet and get confused. To cope with that you have to put a delay between your packet.
 2. If you reset your MCU board while your LCD is writing something without cutting off power, LCD may get first nibble but lose the second 4bit nibble and interprets your initialize data as second nibble data to show on LCD and simply get confused. If LCD had something like software reset it could help but I did not find anything in datasheet. Though I think there is a hardware walkaround

[![ LCD I2C module based PCF8574 Schematic][1]][1]

if you could disconnect K in 8050 transistor and connect LCD Ground to that point then you could disconnect and connect LCD power just by toggle P3 pin through PCF8574 IC when you are initializing your LCD.actually you will lose some control over LCD backlight. you can consider R/W pin too because almost all firmware just write on LCD and simply lower this pin. I bring the purpose schematic in below

[![modified schematic][2]][2]

 in Module simply disconnect ground pin from module and LCD and in LCD board connect K pin to ground as i put the image here

[![disconnect Ground PIN][3]][3]

[![connect Baklight Kathode to Ground PIN][4]][4]

in your Code When you are Initializing write 0xF7 in I2C and Delay for 200 ms then write 0 for and delay 100 ms then do your other Initialization
 Sorry for bad English

  [1]: https://i.stack.imgur.com/6f2NO.gif
  [2]: https://i.stack.imgur.com/slzHn.png
  [3]: https://i.stack.imgur.com/jPhpr.jpg
  [4]: https://i.stack.imgur.com/t0UBC.jpg


message:
Observing USB Gamepad with Arduino?

I have a gamepad which I want to treat as a sensor for my Arduino board. I want Arduino to trigger a certain action based on button pushes from the gamepad. Different buttons, different actions.

The gamepad comes with a USB connector. I cut the the USB cable open, solder it with pluggable pins which are then connected to a breadboard. I supply the gamepad with 5V power from Arduino and connect the USB's Data+ to Arduino's analog input pin (A0). Please check the images below.

I thought by observing the voltage coming from the gamepad's Data+ pin, I can probably determine if a button is being pushed. However, the observable input voltage in Arduino's A0 do not produce any meaningful difference between button push and release.

My question: Is it possible to detect Gamepad's button pushes with this arrangement? If it's possible, where do you think I'm doing wrong?

[![USB Gamepad and Arduino][1]][1]

<!-- 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/V6e4s.png)

<!-- End schematic -->

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

body: As mentioned, the problem is the gamepad you have uses communicates over USB, which requires a USB Host chip to communicate with. However, USB Host shields can be found on eBay (under "arduino USB Host shield") from US$10, and they come with a USB socket, so you could use it easily with another gamepad that hadn't had the connector snipped. This also would allow use with HID devices such as mice and keyboards if you wished, so a worthwhile shield to own.


body:
USB devices make a serial communication, a series of packets of bits are sent and received, which is not beyond your power to learn and talk with. Using a USB Host shield or a chip would be easier (and more costly), but doing it yourself will be much more fun and educational.

Surprisingly, for some USB devices (like a keyboard) you need to poll the data. Nothing will be sent to the host automatically. To find out the protocol they speak, you need to connect the game-pad to a PC and monitor the signals.

Also you need to monitor both D+ and D- signals, they are both used.

Here is a wonderful video by Ben Eater about the USB Keyboards where he goes deep into monitoring the signals and the protocol, can be a good start for your project:  [https://www.youtube.com/watch?v=wdgULBpRoXk][1]

  [1]: https://www.youtube.com/watch?v=wdgULBpRoXk


message:
uint8_t etc as color variable

I am very new to coding and I am attempting to teach myself the best I can.  I have no prior knowledge of coding and am filling in the blanks via YouTube and forums alike.  One place I keep getting hung up on is what seems to be an unsigned integer.

I have tried to figure out how these work (assignment and such) to no avail. I was wondering if anyone could offer some insight for me or at the least a link that gets specific for the Arduino.

I see them used as uint8_t, uint16_t, and uint_32 in various places.  Am I correct that it is an unsigned integer?  Meaning it is a whole positive number only.

The code I have attached is from Adafruit's article on multi-tasking.  I am trying to adapt my sketch for millis() over delay().

          uint32_t Color1, Color2;  // What colors are in use
          uint16_t TotalSteps;  // total number of steps in the pattern
          uint16_t Index;  // current step within the pattern

For instance: on the variable declarations they use these for the color.  I will need to change the colors, but have only seen them expressed in RGB.  They are in every sketch I see, but I am struggling to answer this question on my own.  Thanks in advance for any help.

body: Everything about standard integer types is in <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__stdint.html">`<stdint.h>`</a>


body:
If you search for information about C types on the internet, there will be much help to find, but effectively you are correct. One format of integer types in C take the form:

`uint` / `int`: Signed or unsigned integer. Unsigned integers are stored in simple binary representation, and signed integers are stored in [two's complement][1] form.

`8` / `16` / `32` / `64`: The number of bits to store the value. This means the number of possible values is 2<sup>*x*</sup> where *x* is the number of bits.

`_t`: Simply a suffix to indicate that it is a type name, not a variable.

----

## Colour storage

Colours are generally stored as three components: *red*, *green* and *blue* (or sometimes four, adding *alpha*, the degree of transparency).

If each component is given an unsigned byte to be stored (so it has a value from 0–255), then the total colour size is 24 bits. However, 24 bit integers are not a standard size, so the next bigger size is selected, 32-bit. This also allows room for an alpha component if necessary, but otherwise the spare 8 bits are unused.

### For example:
    | 00000000 | 00000000 | 00000000 | 00000000  | = 32 bits
    | red      | green    | blue     |alpha/empty|

  [1]: https://en.wikipedia.org/wiki/Two's_complement


message:
I'm pretty sure I fried my Arduino Uno. Given my setup, what caused it to be fried? (I can't identify the short)

I was trying to drive a Nema 17 stepper motor using an arduino uno and an A4988 driver. I had it wired up according to this instructable (http://www.instructables.com/id/Drive-a-Stepper-Motor-with-an-Arduino-and-a-A4988-/) at step 2 without the motor power supply wired to the bread board yet. ALSO, I hadn't wired the sleep to reset yet (I just didn't read directions carefully). The board was connected to my computer via USB and I had uploaded the sketch on the instructable to it.

Then, because I misunderstood the directions, I plugged my 12V 8A power supply into the power input on the arduino. All of the sudden, my computer turned off. My computer is fine after restarting, but now the arduino isn't recognized at all by the computer when I plug it in.

Given this information, I am pretty sure that my arduino is fried. However, I can't understand why plugging in the power supply to the power input, which has a voltage regulator, would cause the board to fry.

body:
The Uno is not one "thing" that fails. It has various components, some of which may have failed. I wrote a lengthy page about how to test various parts:

https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board

---

> I plugged my 12V 8A power supply into the power input on the arduino.

Perhaps you reversed the leads, and shorted the USB power to ground, thus causing the PC to turn off? This would probably also blow most of the components on the Uno because they would have had -12V applied to them, assuming it got past the voltage regulator.

However there **is** a reverse polarity protection diode on the power input jack. Did you use that or the `Vin` pin? (or the `Vcc` pin?)

Note that the reverse polarity protection does not protect you if you use the `Vin` pin.


body:
I wonder if you destroyed your Arduino's voltage regulator.

If the Arduino was connected to the stepper motor via the A4988 when you powered the Arduino with a 12V supply, the stepper motor might have drawn current from the Arduino's regulator. This current is likely ~2As, which is far more than the tens of milliamps the Arduino is designed to output. This kind of current draw could quite possibly destroy the regulator on your Uno.

This could also explain why your computer restarted. USB ports on computers are designed to provide an output voltage to their USB devices, so if you provide a voltage on the USB power lines your computer is also driving, you can short your ports if the two voltages are not exactly the same. This is actually why USB cables have the A vs B end design - they mark which side should supply power (A), and which should be powered (B). The Arduino might have provided a voltage on the USB cable's 5V line and thus shorted something in your computer that provides the voltage for your USB ports (I believe Unos are not designed to be powered by both USB and the 12V connectors simultaneously).

If the regulator fried on your Uno, you might have had a voltage that was way off of the expected 5v on the USB port. A well designed USB port will usually try protect itself in a situation like this, often causing the computer to shutdown or the USB bus to deactivate until restarting the computer.

You could check your Uno's voltage regulator with a multimeter or better yet and oscilloscope to see if that is in fact the problem. If so, you could solder a new one on pretty cheaply and quickly. However, there is no guarantee nothing else got fried, in which case buying a new $10-20 Uno looks like a pretty appealing option.


message:
Problems using an arduino with vex motors and motor controller 29

I am using a VEX 2-wire motor with the Motor Controller 29 to use it like a three-wire motor.

I was told that I am able to program it like a servo using the Arduino `Servo` class. When I use the `write()` function to set the power, it works from values around 50-85 in one direction, slowing down the power as I increase the value, but when the value exceeds around 90 then the motor stops working and makes strange clicking sounds. It is not a hardware problem, because the motor works fine in either direction when I plug it straight into a power source.

Does anyone know what my problem is?

body:
VEX motors with Servo library have the following functionality:

0 one direction (full speed)

90 stop

180 opposite direction (full speed)

So at 90, it is trying to remain motionless and hence creating that sound.

btw. You should provide power to motors separately from the Arduino. You might fry your Arduino if you run VEX motors from it. Best solution is to power using 7.2V 3000mAh Flat NiMH High Power Battery Packs.


message:
What happens when there's no space left on SD card?

I'm coding a data logger and I would like to know what happens if there are no bytes remaining to be written using SD library, ie, if the SD card is full of data. The logging would just stop or I would get some nasty error?

body: There doesn't seem to be any definite answer in the library documentation, but I am fairly certain that writes will simply fail, and not cause any sort of corruption. The last log entry may be incomplete, but the file should still be readable.


body:
Open-source is just great. Lets have a look at the source code for SD. [Here][1] is what happens on write of a block.

    /**
     * Write data to an open file.
     *
     * \note Data is moved to the cache but may not be written to the
     * storage device until sync() is called.
     *
     * \param[in] buf Pointer to the location of the data to be written.
     *
     * \param[in] nbyte Number of bytes to write.
     *
     * \return For success write() returns the number of bytes written, always
     * \a nbyte.  If an error occurs, write() returns -1.  Possible errors
     * include write() is called before a file has been opened, write is called
     * for a read-only file, device is full, a corrupt file system or an I/O error.
     *
     */

The source code shows that blocks are allocated from the free list and if there are no more blocks the function will return an error.

  [1]: https://github.com/arduino/Arduino/blob/master/libraries/SD/src/utility/SdFile.cpp#L1164


message:
How to hook up an LED strip to an Arduino

I want to add 6 LEDs  under my Arduino case and have the Arduino Uno pulsate the colors. How do I do this?

[![http://i.imgur.com/klYLoVv.jpg][1]][1]

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

body:
Depends on what they are and how much you don't know :-)

I'd suggest starting off by looking at the tutorials for [NeoPixels][1] and [DotStars][2] on Adafruit's site – that should give you a general idea of how things work. Then take a look at the [FastLED][3] library, it supports a large number of LED strips and has some decent examples.

The FastLED examples that will show up in the Arduino IDE after you have installed the library.

Once you've gotten as far as identifying the strip you have and reading some of the basic tutorials and trying out some of the examples you'll either know how to do it or have some much more specific questions to ask.

OK, after looking at the [info on Amazon][4] and looking more closely at the strip (and the price). I don't think these are individually addressable LEDs. More likely the RGB lines are grounds. So what you would do is to provide a +12V supply on the 12V line and ground one or more the RGB lines to turn on that LED. You could probably control brightness with PWM (pulse width modulation, turning them on and off quickly). The catch here is that the current draw will be more than the Arduino can sink and it's at 12V – two quick ways to kill your board in one tidy package.

You'll need to do more research on this to get the details right, but I think you could use a transistor to do the switching (to protect your Arduino for the 12 V and from the current necessary to drive the LEDs). You would connect an Arduino pin to the base of the transistor to control it. You'd need to select a transistor that can handle the current of all of the LEDs of that color. As a guess I'd figure 60 mA per LED at full brightness (for each color) – this is based on NeoPixels running at 5 V so I could be way off.

If I'm right that these are not individually addressable then the programming would be relatively easy – just turn on the output to turn on the color.

I'd start off by cutting off a strip of the LEDs to experiment with. Use the 12V supply that came with them and see what happens when you connect 12 V to the 12V line and ground one of the color lines. It doesn't look like there is a resistor to limit current, so you should add one to hold the current down. I *think* the LEDs would be wired in parallel, so you'd be looking at needing to supply 6 times the individual LED current. To be safe you could start at around 20 mA and use a 100Ω 1W resistor – you can find an LED resistor calculator [here][5], be sure to select the parallel calculation and use a low current to start with to be safe.

Once you know that the strip works the way you think it does, try adding a transistor to control each color. Then when you've got that working, hook up to the Arduino. Just remember that you will also need to respect the Arduino's current and voltage limits on the digital pins.

[1]: https://learn.adafruit.com/adafruit-neopixel-uberguide/overview
[2]: https://learn.adafruit.com/adafruit-dotstar-leds/overview
[3]: http://fastled.io
[4]: http://www.amazon.com/gp/product/B00MA397GI?psc=1&redirect=true&ref_=oh_aui_detailpage_o06_s00
[5]: http://ledcalc.com


message:
How fast is an Arduino?

Can an Arduino Uno calculate the time that an assembly instruction will take in nanoseconds, not microseconds? I don't want to use a PC, because the calculation will be more accurate using an Arduino, as the processor won't be running other tasks.

If the Arduino can't, is there any way to improve it, or any other open source hardware that can do?

body:
If you're asking "can an AVR measure how long it works on a task" then the answer is yes, but I don't think that's what you're looking for.

If you're asking "can I craft a program that takes a specific amount of time to run" then the answer is also yes. The trick is to look in the datasheet or in the AVR Assembly Instruction manual to see how long each instruction takes in cycles and then multiply that by the MCU's clock period.


body:
> How fast is an Arduino?

Arduino Uno is based on AVR MCU and run at 16 MHz. Due to the processor architecture it can execute almost 1 instruction per clock cycles (62.5 ns). It uses a simple two step pipeline which may require restart if a branch is taken. There are some instructions such as memory access that take more than one clock cycle.

> Can an Arduino Uno calculate the time that an assembly instruction will take in nanoseconds, not microseconds?

It is possible to measure the execution time with a resolution of 4 us with micros(). Please describe what you want to calculate/measure.

For more details on ATmega328p please see the [data-sheet, chap. 6.6 Instruction Execution Timing][1].

  [1]: http://www.atmel.com/images/doc8161.pdf


body:
> I just want to know how much time (in nanosecond example: 14 microsecond and 145 nanosecond ) it'll take for a CMP instruction comparing 2 strings, because in theory it will take less time if the two strings doesn't match.

You can set up a hardware timer (eg. Timer 1) with a prescaler of one, so that each "tick" counts one clock cycle. Thus it can time to a resolution of 62.5 ns if running at 16 MHz.

Then you could read the timer, do your target instruction (eg. compare two strings) and then read the timer again. The difference in counts will be the time (in units of 62.5 ns).

I have a [page about timers](http://www.gammon.com.au/timers) which might help you get started.

---

> ... calculate the time that an assembly instruction will take ...

Generally speaking the C++ compiler does a good job of generating code. You won't necessarily make things faster by writing in assembler and you might make it slower, because compiler-writers know various tricks which you might not.