# Question
Title: 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.

# Answer
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) and `EnableInterrupt.h` 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, 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, 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).

```
/*  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` from arduiniana.org.

**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. 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.\]

```
/*  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, pins PJ0 and PJ1 on an ATmega-2560 board will not report correctly.)

```
/*  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), "  %2d   P%c%d  0x%02x",
           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.

```
/*  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 & 0x%02x |",
            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 & 0x%02x | w & 0x%02x;",
           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 & 0x%02x; // 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(%2d, ioMode); // %2d, 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 |= 0x%02x;", ivect, intmask[ivect]);
      Serial.println(buffi);
    }
  }

  snprintf(buffi, sizeof(buffi), "    PCIFR  |= 0x%02x; // clear PC interrupts if any",
       vecmask);
  Serial.println(buffi);
  snprintf(buffi, sizeof(buffi), "    PCICR  |= 0x%02x; // 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() {
}

```
> 3 votes

---
Tags: arduino-uno, interrupt
---


# Question
Title: 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(){}

```

# Answer
> 2 votes
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*.

---
Tags: library
---


# Question
Title: 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?

# Answer
> 2 votes
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.

---
Tags: serial
---


title: How to have precise measurements

text:
# Question
Title: 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!

# Answer
The ADXL345 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.
> 4 votes

# Answer
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.
> 2 votes

---
Tags: sensors, timers
---


title: Books on Arduino development in C++

text:
# Question
Title: Books on Arduino development in C++
I will be using the Arduino platform with other data acquisition hardware for a school electronics project. I have limited knowledge of C++ syntax.

Are there good introductory to intermediate books that can bring a high school student with some programming experience to proficiency on Arduino?

# Answer
> 1 votes
I'd recommend you go to cplusplus.com. Plenty of tutorial pages and topics to further your knowledge. However, be aware that Arduino uses a variant of **C** designed for microcontrollers (the exact flavour depends on the microcontroller type/family), rather than *C++*, so do be aware that some of the topics are not implementable on an Arduino. That said, I can't think why you'd be using some of the more elaborate C++ exclusive features in a fairly middle-of-road embedded system.

The only thing you need to ignore in C++ is memory allocation specifics - you're limited to the 'original' `malloc()` based functions rather than the all-singing-all-dancing `operator new` from C++. If you are in need of memory allocation functions, malloc is well-documented and a tutorial is only a quick Google away.

Of course I must also point you in the direction of the highly popular Stack Overflow site, part of this Stack Exchange network. While they don't have tutorials, there are plenty of great answers to common questions.

# Answer
> 1 votes
I would start with a standard C++ introduction book to get an understanding for the language. After that I would read a book on object-oriented design and implementation.

There is a lack of books on how to systematically approach programming small scale embedded systems such as Arduino. Due to the restrictions on resources, both processing and memory, C++ has to be used "carefully". There is a need to understand some of the more difficult concepts such as volatile, virtual, ISR, etc.

Reading others code is also a very good way to learn. I would recommend looking at the source code and example sketches to Cosa. This is an OOP framework for Arduino/AVR.

Last but not least - learning by doing!

Cheers!

# Answer
> 0 votes
There is a book called "C Programming for Arduino" by Julien Bayle that introduces it pretty well if you are just getting started at it. I think it's from Packt Publishing.

Another I found interesting is called "Practical AVR Microcontrollers" by Alan Trevennor that gives examples of programming using C without having to get an Arduino.

Otherwise, Stack Exchange is always really great to browse.

# Answer
> 0 votes
I found the Arduino examples a good reference for refreshing/learning C++.

Important Arduino C++ classes are:

To learn more about the syntax of the language, the inventor of C++ has also a couple of videos online.

---
Tags: c++
---


title: Microphone input into Arduino uno R3

text:
# Question
Title: Microphone input into Arduino uno R3
I have an amplifier circuit for a microphone.The output of the circuit(the microphone signal amplified) is connected to the arduino A0 .Now the circuit works(I think ,the output voltage is 4.30 V) and the arduino serial monitor output 875 874... fluctuates with one or 1,2 or more points.The problem is that this value just goes down from 875....800.... .

Is it a correct value?(circuit taken from here http://wiring.org.co/learning/basics/microphone.html)

EDIT: If I put my finger on it the values go up a bit like 792 ,794,800

# Answer
The amplifier circuit you refer to puts out 2.5 volts even without input from microphone. The LM386 has internal circuitry to make the output 1/2 of the +5 volts. Then, audio signal goes above and below the 2.5 volts.

The amplifier circuit will only be putting out the PEAK of your audio signal (because D1 and C2 is a peak detector)

So, when all is quiet, take that ADC value as meaning zero microphone input.
> 0 votes

# Answer
This schematic contains also the OpAmp stage for a microphone. You could take it as reference against the design you are using. The LM386 is basically a more integrated version, iirc.
> 0 votes

---
Tags: arduino-uno, audio
---


# Question
Title: How to setup Uno + xbee shield 1.1 + wee wifi chip?
I am an absolute beginner with electronics and Arduino. I have this hardware:

* arduino uno
* xbee shield 1.1
* wee wifi chip

I've tried to make them work (to connect my Uno to the Internet) but I can't find the right tutorial.

Are there good resources I should look at, or do you know how set this up?

# Answer
As far as the Wi-Fi and Uno is concerned, it's not too difficult. You should download its library for Arduino, which is available on Github and then try its example named *Wifi Client*.

In this example, change your SSID and password, and run serial terminal. It will show you that your Arduino is connected to Wi-Fi and it will also display your IP Address.

Now enter this IP address in your browser and it's like you are pinging your Wi-Fi shield. Soon it will display your analog values. Just make sure your computer and your Wi-Fi chip are connected to the same Wi-Fi connections.
> 2 votes

# Answer
I'd suggest taking this in small hunks. If you haven't done it already, your first step should be to get your development environment together. Use it to create and upload a simple test. The Blink sketch is a common place to start. There are excellent tutorials at the Adafruit site, the have a whole series for getting started with the Arduino.

After you've gotten far enough with the basics to start feeling confident. Try searching for a tutorial for your project. You can often find them by searching on Google – try something like "arduino xbee shield tutorial" – look for descriptions that sound like what you want to do and try reading them. Another good place to look for tutorials is on sites that sell the hardware you're interested in using. For example Adafruit has this tutorial on getting started with the Xbee.

As you work through the tutorials, come back with more questions. As you get more experience it will be easier to ask specific questions and those are easier to answer :-)
> 0 votes

---
Tags: arduino-uno, xbee, web-service
---


title: Multiple Arduino Uno Slaves

text:
# Question
Title: Multiple Arduino Uno Slaves
I am working on an Arduino project where I need more digital and analofgpins than the Uno offers. I was wondering how to hook up multiple Arduinos (4) together so I can use their digital and analog pins. Thanks in advance.

# Answer
> 3 votes
I suggest using a single Arduino Mega. It offers 54 digital I/O and 16 analogue inputs.

I suppose you could also use I2C or SPI to communicate between multiple Uno's.

# Answer
> 0 votes
Ryan Griggs' suggestion of the Mega is likely to be easier and more economical than using multiple Unos. That said can you say more about what you want to do with your proposed design? There are good reasons for distributing the load and the problems are interesting – so it is not obvious that the "right" answer is just to use a bigger central machine.

Besides tightly coupling them with the SPI or I2C you could also consider using Ethernet or Bluetooth. Arduino Ethernet shields tend to be expensive, but there are some wireless devices like the Adafruit Huzzah that are more economical.

You may find this post on I2C by Nick Gammon helpful. There is a similar example in this question.

---
Tags: arduino-uno, digital
---


# Question
Title: Can you connect ACS712 sensor to digital input of Arduino?
I have a home automation project and am looking to use multiple current sensors (ACS712) for multiple appliances. I just need to know whether current is present or not instead of the current value. Is it possible, that I connect the ACS712 sensor to the digital input of Arduino, and get HIGH or LOW via `digitalRead()` function. If not, please suggest an alternative to detect ac current is present or not with digital input i.e. HIGH or LOW that can be read via the `digitalRead()` function.

# Answer
Considering an ATMEGA with a 5V VCC we have:

```
LOW  = < 0.3*VCC = 0,3*5V = 1.5 V
HIGH = > 0.5*VCC = 0,5*5V = 2.5 V

```

You can connect directly to the Arduino if the output of your sensor is higher than 2.5 volts whether current is present or below 1.5 volts if not. This would translate to HIGH or LOW output from `digitalRead()` function respectively.

You need to recalculate this values for the 3 volt version of Arduino, probably in this case is better the comparator solution to ensure up to 3 volts max logic level.

Example circuit as follow, just need to set voltage divider to desired threshold (note this is for 5v case),
> 2 votes

# Answer
Use a comparator for an adjustable threshold and feed the output into the arduino digital pin.
> 0 votes

# Answer
It seems like you could do this with a transistor (if "faking" a digital signal from the ACS712 doesn't work). A simple circuit where the VIOUT of the ACS712 drives the base of a switching transistor connected to a digital pin on the Arduino with an internal pull up might do the trick (assuming that the ACS712 give you a voltage on VIOUT that is proportional to the current).
> 0 votes

# Answer
The Arduino/AVR (for instance ATmega328p, chap. 22) has an analog comparator (D6/AIN0, D7/AIN1 or any analog pin). This could be used with the correct reference voltage.

Cheers!
> 0 votes

---
Tags: digital-in
---


# Question
Title: 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?

# Answer
> 2 votes
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.

---
Tags: arduino-uno
---


# Question
Title: arduino webserver serves single web page to WAN/Internet very very slowly
I have an arduino web server running from a mega 2560 and a wiznet ethernet shield.

It serves the single page just fine (and very fast) to the LAN (192.168.1.50), but serves the same page very, very, slowly when accessed from the WAN/Internet.

I have port forwarding set-up on the modem router so that the Arduino web page can be accessed from the outside world, and it does work, I can see the page from anywhere, but it's page serve rate is impractically slow. The page takes 30 - 45 seconds to load up.

(I have the RaspPi with Apache set-up, also in the house, using the exact same port forwarding settings - with a different port - and it serves pages to the WAN/Internet very fast).

Has anyone any ideas what might be wrong ?

Thank you

# Answer
> 1 votes
I haven't used the ethernet library for a while, but I remember that it served up tiny packets - basically each write call went in its own TCP packet. It sounds like you may have latency issues across the WAN.

You could try using your Apache instance to proxy the Arduino pages. Details are at http://httpd.apache.org/docs/current/mod/mod\_proxy.html I have this running but all my pages are small so I'm not sure how it would behave on larger pages.

# Answer
> 1 votes
The answer is :

I combined all my

```
client.println("<b><font size=+1 color='#CC33FF'>Some text here</font></b><br/>");

```

html statements into much longer statements eg

```
client.println("<b><font size=+1 color='#CC33FF'>Some text here</font></b><br/><a href=\'?s4-all-on' target='x2'>All On</a>   <a href='/?s4-all-off' target='x2'>All Off</a><br/><a href='/?s4-1on' target='x2'>Socket 1 On</a>   <a href='/?s4-1off' target='x2'>Socket 1 Off</a><br/>");

```

This reduced the number of client.println(" "); statements by about one third, which resolved the issue.

# Answer
> 0 votes
This would be a good place to get out tcpdump or WireShark (or any other tool that will let you observe network traffic). If you watch the traffic while you're making the a request that goes to the Arduino (perhaps use a phone to make the request so that it comes from outside) you will be able to observe the TCP/IP transactions and see where the delays are.

---
Tags: web-server, lan
---


# Question
Title: 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.

# Answer
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) 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 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 or could test if your buck converter just passes the voltage on through, as opposed to shutting down when the input voltage is low.

(Note, the AA-battery discharge curves shown above and below are from the powerstream.com's “AA tests” web page.)

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:

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

---
Tags: battery
---


# Question
Title: RF24 tranceivers: trouble with two way communication
I am using RF24 modules with my two Arduinos Leonardo with the RF24 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.

# Answer
> 3 votes
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.

---
Tags: arduino-leonardo, nrf24l01+
---


title: Event driven programming

text:
# Question
Title: Event driven programming
I have ran across a couple of different event libraries that are available on the AVR and Andruino but I am not sure which one is the best option. What I would like to do is design my program in a event driven style but not sure how to go about this.

I have a project that I need to keep lightweight but also in this program I have several actions that can be happening at any given time i.e. Digital Inputs being triggered and I need to run code whenever these events happen.

I found the QP Framework that looked promising but I wanted to get some feedback from some others that might of used this type of library before and might be able to provide some examples and maybe some experiences.

Another site I found here and lists all sorts of different libs

# Answer
You may want to take a look at LMX by David Anderson A Light-Weight Multi-Tasking Executive.

He has a very good set of videos on the code that he did for Dallas Personal Robotics Group (DPRG).

The specific videos for LMX are:
> 1 votes

---
Tags: programming, arduino-mega, threads, events
---


# Question
Title: 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

# Answer
> 2 votes
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

---
Tags: edison
---


title: Arduino code for XBee

text:
# Question
Title: Arduino code for XBee
I am trying to send analog data, from a LM35, using an XBee (series 1 - XB24).

My setup:

* Transmitting Module: XBee with USB explorer+Arduino+LM35 (temperature sensor)
* Receiving Module: XBee with XBee shield+Arduino

I read analog data using the Arduino and send it through the XBee in the USB explorer, then the receiving XBee module receives it and shows it in the serial monitor of the Arduino.

I have tried many ways but I can't reach it and I have figured out that my problem lies in the Arduino code.

So, please can anyone help with some demo code for this project?

# Answer
You probably want to take a look at Robert Faludi's book *Building Wireless Sensor Networks*, published by O'Reilly. He describes, step by step, a very similar project, but without the Arduino.

Or Alasdair Allan's *Distributed Network Data*, also published by O'Reilly, which has a similar project using an Arduino.

Also, take a look at Robert Faludi's blog TMP36 Instructions: Simple Sensor Network.
> 1 votes

---
Tags: xbee
---


title: powering RF on GPIO

text:
# Question
Title: powering RF on GPIO
I have been running a simple RF link between 2 arduini uno recently and everything went faily well. I am now trying a new project with an arduino mini pro (5V/16MHz) and the seeeduino RF link (@315MHz), and I see very odd results : when the transmitter is on USB cable, the link runs ok, but when on a 9V battery (as raw voltage input), I get very very limiter range (a few inches).

Because the setup works on USB, I'm assuming that the current limitation on the GPIO that powers the RF transmitter is not the issue here. It therefore has to be the battery itself or the regulator.

Somehow I need to use a GPIO to shut down the radio during power saving phases. My current design is very basic, I should probably add a transistor to enable power on the RF. I was also thinking maybe the RD oscilliator needs to settle down a bit, I may need to add some delays before starting to send data. I can see on the oscilloscope that the data and power PINs seem to behave correctly, although I have noticed a voltage drop on the power pin which is similar in pattern to the data transmitted (but again this is no issue unless using the 9V battery).

# Answer
As established in the comments, the issues here are powering the module directly from a GPIO pin, which are limited to 20 mA, and potentially the limited current of a 9V battery.

Personally I avoid using 9V batteries in projects, as they are comparatively expensive for the lifetime they provide. There are various boost/step-up converters that make a steady 5V supply from two AA batteries.
> 1 votes

---
Tags: battery, rf, arduino-mini
---


# Question
Title: Why are some of my GSM modules not taking commands?
I posted a couple weeks ago about having a GSM error. I moved past it and the code seemed to be working on my GSM module (I think a SIMCOM). But then I needed to create some more systems and out of a total of 8 GSM modules, my code and setup only work on two of them - despite the fact that they should be identical and from the same supplier.

The following code (thanks to this genius post) works without error to send and receive SMS on two of the boards:

```
#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900 = SoftwareSerial(2,3);

void setup() {
  Serial.begin(19200);
  initializeGSM();
}

void initializeGSM() {
  SIM900.begin(19200);
  Serial.println("Turned on");
  SIM900.print("ATEO\r");
  Response();
  SIM900.print("AT\r");
  delay(1000);
  Response();
  SIM900.println("AT+CMGF=1\r");  // set SMS mode to text
  Response();
  delay(1000);
  SIM900.println("AT+CNMI=1,2,0,0,0\r");
  delay(100);
  Response();
  delay(5000);  // give time to log on to network.
  Serial.println("Ready...");
}

void Response() {
  int count = 0;
  delay(1000);
  Serial.println(SIM900.available());
  while(1) {
    if(SIM900.available()) {
      char data =SIM900.read();
      if(data == 'K'){Serial.println("OK");break;}
      if(data == 'R'){Serial.println("GSM Not Working");break;}
    }
    count++;
    if(count == 100){Serial.println("GSM not Found");break;}
  }
}

void loop() {
  RecSMS();
  delay(2000);
}

void RecSMS(){...}

```

So again, the above code works to set up the module on 2 modules. On the other 6, it simply hangs during the `Response()` call. `SIM900.available()` returns 0 and then says "GSM Not Found." So I tried to initialize the TX pin during setup as:

```
digitalWrite(2, LOW);

```

Which then gives me a promising `SIM900.available()` value of about 63, which corresponds to what a confirmation would be. However, when I print the "data" variable containing the byte read off the GSM module/SIM card, I get a couple bits of garbage like the following output:

Has anyone experienced this problem and knows a way to properly initialize the GSM module?

# Answer
I am owner of this blog whose link you shared, so first of all, I am felling happy that you got something out of it. Now secondly, this code you got from my post is incomplete.

You need to buy that one in order to get the complete code. The code I designed is using AT commands but the above code which you have mixed with your own code is using the Arduino library that's why it's not giving the correct results.

So, either use the complete code from my website or use the Arduino library code only because it has the commands for checking the response, you don't need to use my code to get the response.
> 1 votes

---
Tags: arduino-uno, gsm
---


# Question
Title: 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:

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

# Answer
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…
> 2 votes

# Answer
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
> 0 votes

# Answer
I think you should first check it in simulation and for that install Proteus software and get this Ultrasonic Sensor Library for Proteus and then test your code in simulation.

Once you confirmed that your code is working fine then you can come to the hardware debugging but I think its more probably because of programming issues.
> -1 votes

---
Tags: arduino-uno, sensors
---


title: uint8_t etc as color variable

text:
# Question
Title: 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.

# Answer
> 2 votes
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 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|

```

# Answer
> 0 votes
Everything about standard integer types is in `<stdint.h>`

---
Tags: programming, arduino-ide, sketch, adafruit
---


# Question
Title: 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?

# Answer
> 1 votes
Depends on what they are and how much you don't know :-)

I'd suggest starting off by looking at the tutorials for NeoPixels and DotStars on Adafruit's site – that should give you a general idea of how things work. Then take a look at the FastLED 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 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, 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.

---
Tags: arduino-uno, rgb-led
---


# Question
Title: 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?

# Answer
Open-source is just great. Lets have a look at the source code for SD. Here 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.
> 3 votes

# Answer
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.
> 1 votes

---
Tags: sd-card, datalogging
---


title: Trouble with sleep mode and interrupts

text:
# Question
Title: Trouble with sleep mode and interrupts
**Context**

I am building a small battery powered counting device. As with many other projects like this, saving power is critical. I am therefore trying to utilise the sleep mode wherever possible. This is using a 328P as a standalone MCU running on the 1MHz internal clock

The Hall Effect sensor I am using outputs Vcc when nothing is detected, and Ground when something is detected. It therefore seems well suited to being used as a trigger for an interrupt to wake up the 328P from sleep (so that I don't even need to use a watchdog timer.)

Below is an excerpt from my code. This code does put the processor into sleep as desired. However, from testing I have discovered that the device will not sleep when the magnet is left near the sensor, as its output stays LOW. As I only want to detect pulses of a moving piece of metal, this is wasting power. I only want to wake up when it is initially detected on each cycle.

```
void sleepLoop()
{
  Serial.print("S");

  delay(5);   //scales to 40ms

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  noInterrupts();

  attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);

  interrupts();
  sleep_cpu();

  //The program will continue from here.

  //First thing to do is disable sleep.
  sleep_disable();
}

```

I therefore changed

`attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);`

to

```
attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, FALLING);

```

**PROBLEM**

Now my processor never goes to sleep. For debugging I have put in a serial print at the start of the loop so that I know it has entered this loop of code. Whether `LOW` or `FALLING` is used the 'S' is printed. I only know it is not sleeping because I am measuring the current flow.

I thought the sensor may be going LOW long enough to keep the device awake, but not long enough to register as a count (as I have a debounce in there) so I have checked the output from the sensor with an oscilloscope in case it was momentarily going `LOW`, but I couldn't see any sign of this.

The findings from the oscilloscope make me feel like there is something about the interrupt function that I am overlooking. Any help would be greatly appreciated!

# Answer
> 2 votes
Only low level detect is possible with external interrupt pins (INT0/D2 and INT1/D3) in power down sleep mode. The signal must be low for a number of clock cycles to be detected and the interrupt will detected while the signal is low (and the interrupt is enabled). It is not a transition.

A pin change interrupt could be used instead.

For more details please see chap. 9.5 Power-down Mode and chap. 12. External Interrupts.

Cheers!

# Answer
> 0 votes
There is a more radical alternative, that could yield even higher power savings: use the HAL sensor to trigger a monostable circuit that normally would keep the uC (and the clock source) powered off.

When it starts, get it to update the counter and time the monostable so that it shortly puts the rest of the system back to off.

You can use the eeprom for the counter.

For improved efficiency, get rid of the bootloader and start executing your application right away. If you program from the ISP interface, you do not need the bootloader.

---
Tags: c++, interrupt, sleep
---


title: Decision maker loop problem

text:
# Question
Title: Decision maker loop problem
Today, I've started a decision maker, using a Arduino UNO R3, a button and a RGB led. This project makes a decision for you (yes, no, or maybe) when you don't know your own decision about something.

The code I used in the project is the following one (written by me):

```
#define out OUTPUT
#define in INPUT
#define H HIGH
#define L LOW

int red = 2;
int green = 3;
int blue = 4;

int randomValue = 0;

int button = 5;
int buttonState = 0;

void setup(){
    pinMode(red, out);
    pinMode(green, out);
    pinMode(blue, out);

    pinMode(button, in);
}

void loop(){
    buttonState = digitalRead(button);
    if(buttonState == H){
        randomValue = random(0,4);
        if(randomValue == 1){
            digitalWrite(red, H);
            delay(200);
            digitalWrite(red, L);
            clear();
        }
        if(randomValue == 2){
            digitalWrite(green, H);
            delay(200);
            digitalWrite(green, L);
            clear();
        }
        if(randomValue == 3) {
            digitalWrite(blue, H);
            delay(200);
            digitalWrite(blue, L);
            clear();
        }

    }
}

```

The connections are correct, and the code also. The problem is: when I push the button, the LED starts showing random colors, and what I want is for the LED to show one color per push.

What can I do?

# Answer
> 1 votes
There is one basic concept that you are lacking. At the moment you are looking to see *if* the button is pressed, not *when* the button has been pressed.

Instead of just looking to see if it is HIGH you need to look if it *was* LOW but is *now* HIGH. It's that transition from LOW to HIGH that you need to use as your trigger for when to set the LED colour, and that means remembering the state of the button the last time you went through the loop.

```
buttonState = digitalRead(button);
if (buttonState != oldButtonState) {
    oldButtonState = buttonState;
    if(buttonState == H) {
        // Do your stuff
    }
}

```

`oldButtonState` is defined the same as `buttonState`.

---
Tags: arduino-uno, rgb-led
---


# Question
Title: How can I attach I2C sensors on the small board of Intel Edison?
Sensors like Skin conductance, Body temperature and Heart Rate. Please imagine to talk to a child and keep the answer very simple so I can understand you and you don't lose time to write explanations for your answer.

# Answer
If you're using the mini-breakout board (https://www.sparkfun.com/products/13025), then you can get the I2C connections from the board (connections available through holes under the Edison; you can see them from the backside; see: https://cdn.sparkfun.com//assets/parts/1/0/0/1/1/13025-02.jpg). You can solder headers on or can solder wires directly to the required pins. You can find the pin mapping here: http://iotdk.intel.com/docs/master/mraa/edison.html
> 1 votes

# Answer
Use the I2C breakout board. This will also handle voltage shift from 1.8 V to the sensor voltage level.
> 0 votes

---
Tags: arduino-galileo, edison
---


# Question
Title: Interfacing Gammon's RS485 with computer
I'm using the non-blocking RS485 Gammon's library for Arduino (as shown at http://www.gammon.com.au/forum/?id=11428) to handle the communication between some arduinos. Now I'm having trouble to add a Raspberry Pi (or otherwise a non-arduino platform) to the network.

How can I integrate the Gammon's protocol in a python or processing software?

# Answer
> 0 votes
Open-source and Web-search is just great. This might be what you are looking for.

Cheers!

---
Tags: rs485
---


title: Arduino Uno "MEM CHECK FAIL" error

text:
# Question
Title: Arduino Uno "MEM CHECK FAIL" error
Just followed a tutorial on how to set up ESP8266 with my Arduino Uno R3. I have a serial connection and get a response of the Arduino but I'm stuck now at chapter "first commands".

I have successfully issued the `AT` command and also the `AT+RST` command and got a response. BUT, the response return was "invalid" at its end instead of "ready". Also theres an output "MEM CHECK FAIL!!!"

```
AT

OK
AT+RST

OK

 ets Jan  8 2013,rst cause:2, boot mode:(3,4)

load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

ÃÕMEM CHECK FAIL!!! <<----------------------------- ???
äslrô
Ai-Thinker Technology Co. Ltd.

invalid <<----------------------------------------- should be "ready"

```

Can anyone explain me what that means? Do I have to (re)flash the firmware? And also - are the instructions all the same? I have bought mine from China but it was sold at the same ESP8266 module on Amazon.

# Answer
http://www.agcross.com/2015/09/the-esp8266-wifi-chip-part-1-up-and-running/

According to the tutorial it's an undocumented bug with no fix.

If you change the name, baud, and set up the wifi and password you should be good to go
> 1 votes

---
Tags: arduino-uno
---


title: How fast is an Arduino?

text:
# Question
Title: 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?

# Answer
> 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 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.
> 2 votes

# Answer
> 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.
> 3 votes

# Answer
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.
> 2 votes

---
Tags: arduino-uno, assembly
---


# Question
Title: deprecated conversion from string constant to 'char*'
What does this error means? I can't solve it in any way.

> warning: deprecated conversion from string constant to 'char\*' \[-Wwrite-strings\]

# Answer
> 30 votes
As is my wont, I'm going to provide a bit of background technical information into the whys and wherefores of this this error.

I'm going to inspect four different ways of initializing C strings and see what the differences between them are. These are the four ways in question:

```
char *text = "This is some text";
char text[] = "This is some text";
const char *text = "This is some text";
const char text[] = "This is some text";

```

Now for this I am going to want to change the third letter "i" into an "o" to make it "Thos is some text". That could, in all cases (you would think), be achieved by:

```
text[2] = 'o';

```

Now let's look at what each way of declaring the string does and how that `text[2] = 'o';` statement would affect things.

First the most commonly seen way: `char *text = "This is some text";`. What does this literally mean? Well, in C, it literally means "Create a variable called `text` which is a read-write pointer to this string literal which is held in read-only (code) space.". If you have the option `-Wwrite-strings` turned on then you get a warning as seen in the question above.

Basically that means "Warning: You have tried to make a variable that is read-write point to an area you can't write to". If you try and then set the third character to "o" you would in fact be trying to write to a read-only area and things won't be nice. On a traditional PC with Linux that results in:

> Segmentation Fault

Now the second one: `char text[] = "This is some text";`. Literally, in C, that means "Create an array of type "char" and initialize it with the data "This is some text\0". The size of the array will be big enough to store the data". So that actually allocates RAM and copies the value "This is some text\0" into it at runtime. No warnings, no errors, perfectly valid. And the right way to do it *if you want to be able to edit the data*. Let's try running the command `text[2] = 'o'`:

> Thos is some text

It worked, perfectly. Good.

Now the third way: `const char *text = "This is some text";`. Again the literal meaning: "Create a variable called "text" that is a *read only* pointer to this data in read only memory.". Note that both the pointer and the data are now read-only. No errors, no warnings. What happens if we try and run our test command? Well, we can't. The compiler is now intelligent and knows that we are trying to do something bad:

> error: assignment of read-only location ‘\*(text + 2u)’

It won't even compile. Trying to write to read-only memory is now protected because we have told the compiler that our pointer is to read-only memory. Of course, it doesn't *have* to be pointing to read-only memory, but if you point it to read-write memory (RAM) that memory will still be protected from being written to by the compiler.

Finally the last form: `const char text[] = "This is some text";`. Again, like before with `[]` it allocates an array in RAM and copies the data into it. However, now this is a read-only array. You can't write to it because the pointer to it is tagged as `const`. Attempting to write to it results in:

> error: assignment of read-only location ‘\*(text + 2u)’

So, a quick summary of where we are:

This form is completely invalid and should be avoided at all costs. It opens the door to all sorts of bad things happening:

```
char *text = "This is some text";

```

This form is the right form if you are wanting to make the data editable:

```
char text[] = "This is some text";

```

This form is the right form if you want strings that won't be edited:

```
const char *text = "This is some text";

```

This form seems wasteful of RAM but it does have its uses. Best forget it for now though.

```
const char text[] = "This is some text";

```

# Answer
> 6 votes
To elaborate on Makenko's excellent answer, there is a good reason why the compiler warns you about this. Let's make a test sketch:

```
char *foo = "This is some text";
char *bar = "This is some text";

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  foo [2] = 'o';     // change foo only
  Serial.println (foo);
  Serial.println (bar);
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

We have two variables here, foo and bar. I modify **one** of those in setup(), but see what the result is:

```
Thos is some text
Thos is some text

```

They **both** got changed!

In fact if we look at the warnings we see:

```
sketch_jul14b.ino:1: warning: deprecated conversion from string constant to ‘char*’
sketch_jul14b.ino:2: warning: deprecated conversion from string constant to ‘char*’

```

The compiler knows this is dodgy, and it is right! The reason for this is, that the compiler (reasonably) expects that string constants don't change (since they are constants). Thus if you refer to the string constant `"This is some text"` multiple times in your code it is allowed to allocate the **same** memory to all of them. Now if you modify one, you modify all of them!

# Answer
> 5 votes
Either stop trying to pass a string constant where a function takes a `char*`, or change the function so that it takes a `const char*` instead.

String like "random string" are constants.

# Answer
> 4 votes
Example:

```
void foo (char * s)
  {
  Serial.println (s);
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  foo ("bar");
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

Warning:

```
sketch_jul14b.ino: In function ‘void setup()’:
sketch_jul14b.ino:10: warning: deprecated conversion from string constant to ‘char*’

```

The function `foo` expects a char\* (which it can therefore modify) but you are passing a string literal, which should not be modified.

The compiler is warning you not to do this. Being deprecated it might turn from a warning into an error in a future compiler version.

---

Solution: Make foo take a **const** char \*:

```
void foo (const char * s)
  {
  Serial.println (s);
  }

```

---

> I don't get it. Do you mean *can not* be modified?

Older versions of C (and C++) let you write code like my example above. You could make a function (like `foo`) that prints something you pass down to it, and then pass down a literal string (eg. `foo ("Hi there!");`)

However a function that takes `char *` as an argument is allowed to modify its argument (ie. modify `Hi there!` in this case).

You might have written, for example:

```
void foo (char * s)
  {
  Serial.println (s);
  strcpy (s, "Goodbye");
  }

```

Unfortunately, by passing down a literal, you have now potentially modified that literal so that "Hi there!" is now "Goodbye" which is not good. In fact if you copied in a longer string, you might overwrite other variables. Or, on some implementations you would get an access violation because "Hi there!" might have been put in read-only (protected) RAM.

So the compiler-writers are gradually deprecating this usage, so that functions to which you pass down a literal, must declare that argument as `const`.

# Answer
> 2 votes
I have this compilation error:

```
TimeSerial.ino:68:29: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   if(Serial.find(TIME_HEADER)) {

                         ^

```

Please replace this line:
`#define TIME_HEADER "T" // Header tag for serial time sync message`

with this line:
`#define TIME_HEADER 'T' // Header tag for serial time sync message`

and compilation goes well.

---
Tags: programming, arduino-ide, c
---


# Question
Title: In UART, what mechanism sets the "new data received" flag back to 0?
I was reading documentation on UART on AVR and it looks simple: when a flag (bit `RXC0` of register `UCSR0A`) is set to 1, it means the micro controller has new data for you, and you read this from register `UDR0`.

But something boggles my mind: How does the micro controller know that we have read the data? Or, in other words, after it received the first byte on UART, the flag is set to 1, but when is it set back to 0?

# Answer
> 2 votes
The ATmega328p data-sheet describes the setting of RXCn:

### Bit 7 – RXCn: USART Receive Complete

> This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXCn bit will become zero. The RXCn Flag can be used to generate a Receive Complete interrupt (see description of the RXCIEn bit).

The hardware seems to keep a register the size of the receive buffer. Incremented when received and decremented when read. It is only one level so the size is 0..1, i.e. one bit.

Actually there is two registers; one for possible incoming data and one for the latest data until read.

Cheers!

More details in ATmega328p data-sheet, chap. 19 USART0

---
Tags: avr, uart
---


# Question
Title: Debugging my Stepper Motor Driver circuit
I'm using the Pololu DRV8825 Stepper Motor Driver to control a NEMA 17 Steppermotor with an Arduino Uno. According to the Pololu website, the circuit should be wired as follows:

I did, however, deviate from this exact sketch a little bit:

1. The Arduino (microcontroller) is powered by a USB cable connected to the computer
2. I connected the 5V pin on the arduino to the + rail on a breadboard. I then connected two wires on this rail to the **RESET** and **SLEEP** pins on the driver.
3. I'm using a 9V battery to power the motor.
4. I've connected the **DIR** and **STEP** pins to Arduino Uno pins 12 & 13, respectively.

Consequently, I coded and uploaded the following sketch:

```
int stp = 13;  //connect pin 13 to step
int dir = 12;  // connect pin 12 to dir
int a = 0;     //  gen counter

void setup()
{
  pinMode(stp, OUTPUT);
  pinMode(dir, OUTPUT);
}

void loop()
{
  if (a <  200)  //sweep 200 step in dir 1
   {
    a++;
    digitalWrite(stp, HIGH);
    delay(10);
    digitalWrite(stp, LOW);
    delay(10);
   }
  else
   {
    digitalWrite(dir, HIGH);
    a++;
    digitalWrite(stp, HIGH);
    delay(10);
    digitalWrite(stp, LOW);
    delay(10);

    if (a>400)    //sweep 200 in dir 2
     {
      a = 0;
      digitalWrite(dir, LOW);
     }
    }
}

```

**RESULT**
The stepper motor does not turn. Instead, it just hisses at a high pitch. After a short while, the driver gets very hot.

**THINGS I'VE TRIED**

1. I double checked to make sure that connected stepper wires pairs are properly connected to the "A" pins and "B" pins on the driver.
2. I tried reversing the A1-A2 pair and B1-B2 pair in all possible combinations. All combinations produce the same result as above.
3. I tried increasing the motor power supply to 12V (8 alkaline AA batteries). The same result occurs.
4. I double checked to make sure the 100microF radial electrolytic capacitor is connected with the long end to the positive motor supply and short end to the negative motor supply (on a different breadboard rail than the logic power supply, of course).
5. I tried using the 3.3V pin instead of the 5V pin to connect to SLEEP and RESET on the driver. Again, the same result occurs.

I'm not really sure what to try next to debug my circuit.

**My Hunch:**

I do, however, have one suspicion based on a little warning box on the pololu website which reads:

> **Caution:** Installing the header pins so that the silkscreen side is up and the components are down can limit the range of motion of the trimpot used to set the current limit. If you plan on installing the header pins in this orientation, please set the current limit before soldering in the pins.

The way I soldered the headers onto the driver looks like the bottom left corner of the picture below:

**My Question:**
Given that my stepper motor requires 1.7A current, is there anything I can do to improve this circuit to make it work? Did I make any mistakes? Is there anything else I should try or check? Did I solder the header in the wrong way?

# Answer
I had this same issue when setting up this circuit with this code and driver on an Arduino Uno. All else was fine, but the current for the motor was set WAY too high on the driver from the factory. The VREF was 1.7 volts, and it needed to be around .5 for the motor I was using. As I set the VREF to the appropriate voltage, the motor started to spin as it should and stopped hissing.

I know this post is old, but I hope that this helps someone else. Pololu has a great video (and documentation in general) for setting the appropriate voltage on most of their drivers on the product page here: DRV8825 Stepper Motor Driver Carrier, High Current.
> 6 votes

# Answer
**A couple things I noticed first:** This is one of the best formatted questions I've ever seen... :) Anyway, your circuit looks fine to me except for a few things:

> **Warning:** This carrier board uses low-ESR ceramic capacitors, which makes it susceptible to destructive LC voltage spikes, especially when using power leads longer than a few inches. Under the right conditions, these spikes can exceed the 45 V maximum voltage rating for the DRV8825 and permanently damage the board, even when the motor supply voltage is as low as 12 V. One way to protect the driver from such spikes is to put a large **(at least 47 µF) *electrolytic* capacitor across motor power (VMOT) and ground** somewhere close to the board.

*(Added some italic/bold myself, quote from product page.)*

Capacitors are cheap ($1.50 on eBay from US), and although new drivers are too, it's generally a good idea to build it right. There's nothing more annoying than waiting for shipping on something you shouldn't have had to fix.

Additionally, battery power (especially AAs) can be bulky if not done right, and may not provide enough current. Note that in a series configuration that **it will provide the voltage of 8 AAs, but only the current of one.** You can't run a 1.7 A motor off of a single AA's current. Stab in the dark guess: you'll need ~80-100 AAs to provide enough current and voltage. I'm too lazy to measure the internal resistance and actually calculate it.

**Suggested solution:** There are a million things that could go wrong. Without being there, I'm betting that your delay function is too short. What this will do is not provide enough time for the motor to move, thus it staying still. This would still use a lot of current (50% of the time it's full current to motor coils), therefore it would make the driver hot. (**Note on heat:** *...to supply more than approximately 1.5 A per coil, a heat sink or other cooling method is required...* -Product page: you'll need a heatsink to cool your chip down.) Also note that some heat is normal; a general rule of thumb is if it's too hot to hold your thumb on it for a few seconds, you need more cooling. Remember that the more it's used, the hotter it'll get, so keep this in mind when deciding if you want to add a heatsink.

**tl;dr:** You need to increase the delay time and provide more current than you have currently.
> 2 votes

# Answer
I don't think your batteries were too low in current capacity, your delay time is not too short, at 10 +10 ms per clock pulse, you are only talking about 50 steps per second, that's not all that fast. I've written programs where I have had to go to microseconds to get enough rpm out of my stepper.

First, take everything out of your loop except the digitalwrite high, delay digitalwrite low and delay lines. Then the program "should" just spin the motor continuously in one direction. That way you are sure you don't have a logic issue. Second, did you check to see if you didn't hook up pin 12 and 13 backwards, such that you are telling the driver to change direction every 10 ms instead of stepping? The sound it makes would be more like a buzz or vibration, usually a soft, staticy hiss is when the motor is enabled, but not getting a step pulse.

Finally, this post is about 18 months old, it is considerate and helpful to others to explain how you solved the problem (assuming you figured it out).
> 2 votes

# Answer
The one thing that helped me was NOT to connect GND to stepper board from microcontroller (bottom black line from schematic posted in first post).

If it was connected, driver would draw 12V@3A immediately and gets freaky hot. Also motor didn´t turn at all.
> 1 votes

---
Tags: motor
---


title: Audio Visualizer (not working properly)

text:
# Question
Title: Audio Visualizer (not working properly)
**Parts**

* Arduino Uno R3 (Atmega328 - assembled)
* Adafruit Bicolor LED Square Pixel Matrix with I2C Backpack
* Electret Microphone Amplifier - MAX4466 with Adjustable Gain
* Half-size Breadboard
* Breadboarding wires

**Description**
I have been following the build guide for the "Piccolo Music Visualizer" on the Adafruit website (https://learn.adafruit.com/piccolo?view=all), using all of the same components and code (following the guide exactly as shown). I first tested the 8x8 matrix to see if it was working properly, and it works beautifully. The problems started when I wired up the electret microphone...

In regard to how I wired this to the breadboard, I followed the example for the R3 on the Adafruit guide (since that's my current version):

**Note**
The files (code) used for this project are found here: (https://github.com/adafruit/piccolo). The ffft file is supposed to be saved to the library (this worked for me). The Piccolo file is supposed to be saved to the Sketchbook (this did not work for me - kept giving error messages when trying to reference it). I instead copied the code found in the Piccolo file, and saved it as a new sketchbook file. Let me know if this might be the cause of the problem. This is my first arduino project, so I am still trying to figure out how the IDE works.

**Problem**
The electret microphone is supposed to pick up audio and the LED matrix should display a waveform based on the loudness and frequency of the audio. Instead, I only have 2 bars on the bottom left lighting up (the effect is static - wont respond to volume or frequency changes). Oddly, when pulling out the microphone from the breadboard, the waveform begins displaying as it should, but in a glitchy/unstable form. I figured the problem was with the adjustable gain on the microphone, but no matter how much I adjust the screw only the 2 bars are affected and still static (when adjusted to the left only green LED, in middle is green and orange, to the right is red/orange/green on the matrix).

A little confused as to what the problem could be... is the microphone broken, code malfunctioning, wiring incorrect, etc.

**Pictures to reference** (DropBox link)**:**
\- ***See comment below for link*** (must have *10 rep* to use more than *2 links* in post)
(zip file contains **3** pictures: "*wiring*", "*when\_on*", "*pulling\_out\_mic*")
Photos are over 2MB so I couldnt upload here.

# Answer
> 0 votes
It sounds like a dry joint; the fact that the LED matrix seems to work 'better' when you're fiddling with the microphone board makes me think that the problem lies entirely with that little board.

Try adding more solder; the more the merrier.

---
Tags: arduino-uno, led, arduino-ide, audio
---


# Question
Title: android app to control arduino using usb
I am trying to figure out how i could make an android app like this one, https://www.youtube.com/watch?v=cVj0jqOlGXo but instead of transmitting through bluetooth it would transmit it through a usb cable that plugs from my phone directly into my arduino.

# Answer
I think you may want to look *USB Serial port communication in android*. Some googling will help here's a nice example of such work, described in detail:

http://felhr85.net/2015/01/09/a-dirty-and-quick-example-of-serial-port-communication-in-android/

And in case the codes/that source gets lost, here is the GitHub link of the developer: https://github.com/felHR85/SerialPortExample
> 1 votes

---
Tags: usb
---