message:
Serial Monitor Suddenly Doesn't Work

I have had this problem a few times, it seems the Arduino IDE and the serial monitor is incredibly unstable, unless it's user error but judging from the fact that I hadn't even touched anything before it broke, I would say it's not me.

It was working the night before but this morning it just wouldn't print anything to the serial monitor from my code, however if I start one of the communication example codes like the ASCII example, it prints fine...I'm using the arduino uno, but I have a couple of dues too, so I tried the script on the due and it printed fine to the serial monitor.

Here is my code, could someone check my code and see if they can print to the serial monitor or not?

    /*
       Pins:

       RTC:
       5V to VCC
       GND to GDN
       A4 to SDA
       A5 to SLC
    */

    #include <Wire.h>
    #include "RTClib.h"

    #if defined(ARDUINO_ARCH_SAMD)
    // for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
    #define Serial SerialUSB
    #endif

    RTC_DS1307 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    //Words     //0      //1     //2    //3     //4     //5     //6    //7      //8      //9     //10   //11      //12      //13        //14        //15       //16       //17         //18        //19        //20      //21       //22    //23     //24                    //25//26 //27
    char* w[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Thirty", "Forty", "Fifty", "Keeg Jo And Mat 2016", "", " ", "Good",
                 //28       //29         //30       //31     //32    //33  //34       //35    //36       //37  //38
                 "Morning", "Afternoon", "Evening", "It Is", "Past", "To", "Quarter", "Half", "O'Clock", "AM", "PM"
                };

    //End Words

    int timeType = 0;
    int _hour = 0;

    int dayInput = 0;
    int hourInput = 0;
    int minuteInput = 0;

    int iDay = 0;
    int iHour = 0;
    int iMinute = 0;

    void setup () {

    #ifndef ESP8266
      while (!Serial); // for Leonardo/Micro/Zero
    #endif

      Serial.begin(57600);
      pinMode(11, INPUT);//Minutes
      pinMode(12, INPUT);//Hours
      pinMode(13, INPUT);//Day

      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
        //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        //rtc.adjust(DateTime(2016, 3, 11, 10, 51, 0));
      }

      //rtc.adjust(DateTime(2016, 3, 11, 1, 0, 50));
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    }

    void loop () {
      DateTime now = rtc.now();

      minuteInput = digitalRead(11);
      hourInput = digitalRead(12);
      dayInput = digitalRead(13);

      if (minuteInput == HIGH) {
        Serial.println("Minute");
      } else if (hourInput == HIGH) {
        Serial.println("Hour");
      } else if (dayInput == HIGH) {
        Serial.println("Day");
      }

      Line();

      if (now.minute() == 0) {
        timeType = 0;
      } else if (now.minute() > 0 && now.minute() <= 20) {
        timeType = 1;
      } else if (now.minute() > 20 && now.minute() < 50 && now.minute() != 30 && now.minute() != 45) {
        timeType = 0;
      } else if (now.minute() >= 50 && now.minute() < 60) {
        timeType = 2;
      } else if (now.minute() == 30) {
        timeType = 3;
      } else if (now.minute() == 45) {
        timeType = 4;
      }

      ps("Time Type: ");
      pi(timeType);

      Line();
      Line();

      //Greeting
      p(27);
      Space();
      if (now.hour() >= 0 && now.hour() < 12) {
        p(28);
      } else if (now.hour() >= 12 && now.hour() < 18) {
        p(29);
      } else if (now.hour() >= 18 && now.hour() < 24) {
        p(30);
      }

      Line();
      Line();

      //Time (It Is) Time Type 0
      if (timeType == 0) {
        Itis();
        hours(0);
        Space();
        _minutes();
        OClock();
      }

      //Time (Past) Time Type 1
      if (timeType == 1) {
        Itis();
        _minutes();
        Past();
        hours(0);
        OClock();
      }

      //Time (To) Time Type 2
      if (timeType == 2) {
        Itis();
        _minutes();
        To();
        hours(0);
        OClock();
      }

      //Time (Half Past) Time Type 3
      if (timeType == 3) {
        Itis();
        p(35);
        Past();
        hours(0);
      }

      //Time (Quarter To) Time Type 4
      if (timeType == 4) {
        Itis();
        p(34);
        To();
        hours(1);
      }

      //AM/PM
      AMPM();

      Line();
      Line();

      //Day
      //Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
      ps(daysOfTheWeek[now.dayOfTheWeek()]);

      Line();
      Line();

      pl(24);

      Serial.println("--------------------------------------------------");
      Serial.println("--------------------------------------------------");

      delay(1000);

    }

    //------------------------------------------------

    void Line() {
      pl(25);
    }

    void Itis() {
      p(31);
      Space();
    }

    void Past() {
      Space();
      p(32);
      Space();
    }

    void To() {
      Space();
      p(33);
      Space();
    }

    void Space() {
      p(26);
    }

    void OClock() {
      DateTime now = rtc.now();
      if (now.minute() == 0 || now.minute() == 60) {
        Space();
        p(36);
      }
    }

    void AMPM() {
      Space();

      DateTime now = rtc.now();

      bool am = false;

      if (now.hour() > 12) {
        am = false;
      } else {
        am = true;
      }

      if (am) {
        p(37);
      } else {
        p(38);
      }
    }

    void p(int i) {
      Serial.print(w[i]);
    }

    void pl(int i) {
      Serial.println(w[i]);
    }

    void ps(char* i) {
      Serial.print(i);
    }

    void pi(int i) {
      Serial.print(i);
    }

    void _minutes() {
      DateTime now = rtc.now();
      int minutes = 0;

      if (timeType == 2) {
        minutes = 60 - now.minute();
      } else {
        minutes = now.minute();
      }

      int i = minutes;

      if (i <= 20 && i != 0) {
        p(i);
      } else if (i > 20 && i < 30) {
        p(20);
        Space();
        p(i - 20);
      } else if (i > 30 && i < 40) {
        p(21);
        Space();
        p(i - 30);
      } else if (i > 40 && i < 50 && i != 45) {
        p(22);
        Space();
        p(i - 40);
      } else if (i > 50 && i < 60) {
        p(23);
        Space();
        p(i - 50);
      } else if (i == 30) {
        p(35);
      } else if (i == 40) {
        p(22);
      } else if (i == 50) {
        p(23);
      }

    }

    void hours(int m) {
      DateTime now = rtc.now();

      if (now.hour() > 12) {
        _hour = now.hour() - 12;
      } else {
        _hour = now.hour();
      }

      _hour = _hour + m;

      p(_hour);
    }

body:
      //rtc.adjust(DateTime(2016, 3, 11, 1, 0, 50));
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

Every time you reset the Arduino, the RTC clock will be set back to the date/time you compiled the sketch. Surely you don't want that?

---

The serial monitor is not at all unstable, as you agree when you try a different sketch. Therefore your sketch has a bug, which you need to find.

One possible issue is hardware. The default Wire library will hang if communications are lost when doing a read. Can you describe your clock hardware? Is it a chip you soldered yourself? A board? If so, which one? Do you have pull-up resistors on SDA/SCL?

There is an [alternate I2C library](http://dsscircuits.com/articles/arduino-i2c-master-library) that you could try.

---

Your method of printing is certainly unusual. You call, for example:

    Line ();

When you could just as easily (and a lot more readably) call:

    Serial.println ();

Similarly for `Space` and so on.

---

Still, despite the very hard-to-read code, I can't see any loops that might cause printing to fail. I suggest you comment out the calls to `rtc.now()` and test it. If it works, that confirms you have a clock issue, not a printing issue.

I note that you have multiple calls to:

    DateTime now = rtc.now();

... sprinkled throughout your code. Surely you only need to read the time once, per loop?

Put the `now` variable outside loop, and call it once only, like this:

    DateTime now;

    void loop () {
      now = rtc.now();

Then remove the other calls to `rtc.now()`.

---

I found when I tested (without a RTC connected) that it did indeed hang. But that was the `rtc.now()` call failing. If you comment that out, it prints fine.

eg.

<!-- language-all: lang-none -->

    Minute

    Time Type: 0

    Good Morning

    It Is Six Twenty Eight AM

    Keeg Jo And Mat 2016
    --------------------------------------------------
    --------------------------------------------------
    Minute

    Time Type: 0

    Good Morning

    It Is Six Twenty Eight AM

    Keeg Jo And Mat 2016
    --------------------------------------------------
    --------------------------------------------------

That shows it is definitely a clock issue, not a serial printing issue.


sender: user

message:
Is this method to a String from a function going to cause memory corruption?

I'd like to define a function such that I return a string and a boolean indicating whether the result is valid. Like this:

    bool getStringOrTimeout(String *s) {
      ...
      if (timed_out) {
        return false;
      } else {
        *s = String(<some value>);
        return true;
      }
    }

Is this going to cause a memory problem because the string is allocated on the stack and deallocated when it leaves scope, or is this okay?

sender: assistant

body:
You are better off passing the string by reference, like this:

    bool getStringOrTimeout(String & s)
    {
      if (timed_out)
        return false;
      s = "foo";
      return true;

    }

That means the *caller's* string will be modified. And you no longer need to pass down a pointer to a string.


message:
Arduino metronome - Change time signature on button press

/**************************************/
    const int lowestPin = 1;//the lowest one attach to
    const int speaker = 13;
    int ts = 4;//how many beats you want
    int count = 1;
    const int keyPin = 12;
    int buttonState = 0;
    int bpm = 120;
    /**************************************/
    void setup()
    {
      for (int thisPin = 1; thisPin <= ts; thisPin++)
      {
        pinMode(thisPin, OUTPUT); //initialize thisPin as an output
        pinMode(6, INPUT);

      }
      pinMode(keyPin, INPUT);
    }

    /****************************************/
    void loop()
    {

      //iterate over the pins
      //turn the led on from lowest to the highest

      if (digitalRead(keyPin) == HIGH && ts == 2) {
        ts = 3;
        delay(2000);
      }

      else if (digitalRead(keyPin) == HIGH && ts == 3) {
        ts = 4;
        delay(2000);
      }

      else if (digitalRead(keyPin) == HIGH && ts == 4)
      {
        ts = 2;
        delay(2000);
      }

      for (int thisPin = 1; thisPin <= ts; thisPin++)
      {

        bpm = pulseIn(6, HIGH);

        pinMode(13, OUTPUT);
        if (ts > 4)
        {
          if (count > 3)
            for (int a = 4; a <= ts; a++) {
              digitalWrite(a - 3, HIGH);
            }

        }
        else
          digitalWrite(thisPin, HIGH);

        if (count == 1)
          tone(13, 1500, 100);
        else
          tone(13, 1000, 100);

        delay(bpm - 52);
        pinMode(13, INPUT);
        digitalWrite(thisPin, LOW);

        count++;
        if (count > ts)
          count = 1;

      }

    }

I am trying to make a metronome using Arduino Uno, with 4 LEDs, each LED is a beat. I want to change the time signature every time I press the pushbutton, so that there are different number of beats per measure, but when I do press the button, it runs the code for 2 and 3 beats per measure once, and then goes back to its default, 4 beats per measure.

Sometimes, it even changes without pressing the button, randomly. I am using a 220 ohm resister instead of 10, as 10 starts much more randomly than the 220.

[![Metronome project picture][1]][1]

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

body:
You must have resistors in series with the LEDs. See [The care and feeding of LEDs](http://www.thebox.myzen.co.uk/Tutorial/LEDs.html). 330 ohms in series with each LED would be about right in your situation.

With no resistors you are drawing far too much current from the output pins. That would drop the voltage and the processor would reset. Thus it goes back to the default of 4 beats per measure.

It also damages both the processor and the LEDs.

You can tell if the processor resets by putting extra code into `setup`. For example, after setting the pins to outputs:

     for (int i = 0; i < 10; i++)
        {
        digitalWrite (3, HIGH);
        delay (200);
        digitalWrite (3, LOW);
        delay (200);
        }

If you see pin 3 flashing 10 times, you know the processor has reset.

---

I think your problem now is that you have a floating input for the switch. When I tried your sketch, with a couple of modifications, it worked fine.

My code:

    /**************************************/
    const int lowestPin = 1;//the lowest one attach to
    const int speaker = 13;
    int ts = 4;//how many beats you want
    int count = 1;
    const int keyPin = 12;
    int buttonState = 0;
    int bpm = 120;
    /**************************************/
    void setup()
    {
      for (int thisPin = 1; thisPin <= ts; thisPin++)
      {
        pinMode(thisPin, OUTPUT); //initialize thisPin as an output
        pinMode(6, INPUT);
      }
      pinMode(keyPin, INPUT_PULLUP);
    }

    /****************************************/
    void loop()
    {

      //iterate over the pins
      //turn the led on from lowest to the highest

      if (digitalRead(keyPin) == LOW && ts == 2) {
        ts = 3;
        delay(2000);
      }

      else if (digitalRead(keyPin) == LOW && ts == 3) {
        ts = 4;
        delay(2000);
      }

      else if (digitalRead(keyPin) == LOW && ts == 4)
      {
        ts = 2;
        delay(2000);
      }

      for (int thisPin = 1; thisPin <= ts; thisPin++)
      {

        bpm = pulseIn(6, HIGH);
        //bpm = 1000;

        pinMode(speaker, OUTPUT);
        if (ts > 4)
        {
          if (count > 3)
            for (int a = 4; a <= ts; a++) {
              digitalWrite(a - 3, HIGH);
            }
        }
        else
          digitalWrite(thisPin, HIGH);

        if (count == 1)
          tone(speaker, 1500, 100);
        else
          tone(speaker, 1000, 100);

        unsigned long now = millis ();
        while (millis () - now < (bpm - 52))
          {
          // quit delay if switch pressed
          if (digitalRead(keyPin) == LOW)
            break;
          }

        pinMode(speaker, INPUT);
        digitalWrite(thisPin, LOW);

        count++;
        if (count > ts)
          count = 1;

      } // end of for each pin

    } // end of loop

Note that the input from the switch is now INPUT_PULLUP which means it is pulled HIGH by an internal resistor. Thus, the tests are now for `== LOW` rather than `== HIGH`.

Also, instead of a delay for the timing of the metronome, I changed it to testing `millis()` and seeing if time is up. Otherwise you have to hold the switch down for the entire time that a cycle repeats.


message:
Understanding the contents of a library in C

So this is a question not just about the #include <avr/io.h> but most all includes you find while programming in C.

So I understand a library is prewritten code and when you include that library are you able to used certain function that are included in that library.

What I have always wanted to know is: where can you find the "instruction set", in C, for these libraries?

How can I find out what commands are available for me to use with this library?

hope this makes sense.

thank you everyone.

body:
> What I have always wanted to know is: where can you find the "instruction set", inc C, for these libraries?

The libraries are usually found in the `libraries` sub-folder under your sketchbook folder (wherever that is). There is also another `libraries` folder inside the IDE install folder for the "official libraries".

> How can I find out what commands are available for me to use with this library?

Usually the library documents them in one way or another. Try looking inside the `.h` file used by the library to see what functions are exposed.


message:
Function of rxAlign parameter in the PCD_ReadRegister function in MFRC522 Library

I'm trying to port the MFRC522 Arduino library (from [GitHub][1]) to the ARM MCUs.
My problem is with the PCD_ReadRegister function:

    /**
     * Reads a number of bytes from the specified register in the MFRC522 chip.
     * The interface is described in the datasheet section 8.1.2.
     */
    void MFRC522::PCD_ReadRegister( byte reg,  ///< The register to read from. One of the PCD_Register enums.
            byte count,  ///< The number of bytes to read
            byte *values, ///< Byte array to store the values in.
            byte rxAlign ///< Only bit positions rxAlign..7 in values[0] are updated.
            ) {

     if (count == 0) {
      return;
     }
     //Serial.print(F("Reading "));  Serial.print(count); Serial.println(F(" bytes from register."));
     byte address = 0x80 | (reg & 0x7E);  // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
     byte index = 0;       // Index in values array.
     SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
     digitalWrite(_chipSelectPin, LOW);  // Select slave
     count--;        // One read is performed outside of the loop
     SPI.transfer(address);     // Tell MFRC522 which address we want to read
     while (index < count) {
      if (index == 0 && rxAlign) {  // Only update bit positions rxAlign..7 in values[0]
       // Create bit mask for bit positions rxAlign..7
       byte mask = 0;
       for (byte i = rxAlign; i <= 7; i++) {
        mask |= (1 << i);
       }
       // Read value and tell that we want to read the same address again.
       byte value = SPI.transfer(address);
       // Apply mask to both current value of values[0] and the new data in value.
       values[0] = (values[index] & ~mask) | (value & mask);
      }
      else { // Normal case
       values[index] = SPI.transfer(address); // Read value and tell that we want to read the same address again.
      }
      index++;
     }
     values[index] = SPI.transfer(0);   // Read the final byte. Send 0 to stop reading.
     digitalWrite(_chipSelectPin, HIGH);   // Release slave again
     SPI.endTransaction(); // Stop using the SPI bus

    } // End PCD_ReadRegister()
I read the datasheet several times & can't understand what's the function of this parameter!
Based on datasheet for reading a register from rc522:
[![enter image description here][2]][2]

  [1]: https://github.com/miguelbalboa/rfid
  [2]: https://i.stack.imgur.com/IZuzZ.jpg

body:
Concerning the image in your post about 'SPI Read Data', that simply says the first byte received over MISO is discarded, which is done in `PCD_ReadRegister()` right before the `for` loop, and then `n` bytes are read, with 0 transferred the last time to stop reading.

A quick look at the library and datasheet shows that the `rxAlign` argument is used in identifying the first valid bit in the first received byte. `txLastBits` serves a similar purpose, only for transmission of the final byte. Both are written to `BitFramingReg` of the MFRC522 and are necessary for bit-oriented frames between the MFRC522 and a card/tag.

For example, in the function you have above, if `rxAlign = 3`, it means only bits 7 to 3 are valid in the first **received byte**, extracted with bit mask `11111000`. So the first **valid 'byte'** comprises bits 7 to 3 of the first received byte concatenated with bits 2 - 0 of the next received byte. Similarly, in transmission, `txLastBits` indicates the number of bits of the last byte that are to be transmitted to the card/tag. In both cases, what is transmitted or received over the RF field may not be a multiple of 8, hence the need for these arguments and `BitFramingReg`.

Anyways, this shouldn't interfere at all with porting the library. Simply replace the Arduino-specific functions/interfaces and allow the library's existing logic to remain as is.

----------

**EDIT**

I'll try to answer your questions:

 - In this context, 106kBd refers to the data rate between the RC522 and a card, and not between the RC522 and the MCU. The maximum is about 848kBd, i think. Check the datasheet for more details.
 - Bit-oriented frames are **necessary** for the anti-collision process. Superimposed bits in the Manchester encoding, when several cards attempt to communicate with the RC522 at once, require that individual bits be processed as opposed to the usual byte-sized units. Look up anti-collision techniques.
 - Anticollision is necessary if the same reader will possibly have multiple tags within its range. From an IEEE article:

> Tag collisions can impose a major inefficiency in RFID systems, resulting in low identification rates, short reading range and ineffective resource utilization. They are more problematic in passive tags due to limitations on power and functionality.

So, if you will be presenting only one card at a time, then you should be safe without implementing anticollision in your code. Else, I'm afraid you have no choice unless you want to confuse the reader.

If all you want to do is read UIDs and read from/write to blocks on a card (one at a time), you may want to try porting this straightforward [MFRC522 UART library][1], which doesnt implement anitcollision, by the way.

If you still want to port the SPI-based library, then, a few suggestions:

You want to replace the SPI interface with UART. This is low-level stuff, all contained within a few functions like `PCD_ReadRegister()`, `PCD_WriteRegister()` and a few others. These functions serve higher-level functions, which have no clue of their internal implementation, but expect certain behaviour from them. Swap the SPI functions for their UART equivalents, as soon as you understand how to talk to the reader over UART. Once your ARM UART functions behave exactly like the SPI functions, your work is almost done; there is no need to learn the reason for everything in the higher-level functions since they dont relate to anything interface-specific. This includes everything concerning `rxAlign` and whatnot. Good luck :).

  [1]: https://github.com/zodier/MFRC522-UART-Arduino


message:
RGBW LED strip: which components are required?

I'm brand new to this community, and in electronics as well.

I'm a software developer and I want to start a new journey with a project in mind: I want to control a 5 meters addressable LED strip for my living-room.

I need all the components for this project... I already know eclipse and Java world, but I need help in choosing the components for the project:

- which Arduino (starter package maybe?)
- LED strip (`smd 5050` on `sw2812b`, `sk6812`, `APA104`...) more than 60 LEDs/m
- Power Supply for the project

Can you point me to the right direction, posts that can be useful to me, so I can start on good basis?

body:
I like the `ws2812` RGB LEDs with integrated controller. They can be found on [adafruit.com][1], e.g. here: [Adafruit NeoPixel NeoMatrix 8x8][2].

There are some good tutorials on adafruit.com:

 - https://learn.adafruit.com/adafruit-neopixel-uberguide/overview
 - https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices
 - https://learn.adafruit.com/adafruit-neopixel-uberguide/neomatrix-library

Choosing your Arduino you have to keep in Mind that the [Arduino Due][3] runs at 3.3 V, while the [Arduino Mega][4] runs at 5 V. The `ws2812`. But you can use a [level shifter][5] to connect an Arduino Due to the `ws2812`.

Your Arduino is powered via USB, the LED matrices / stripes need their own power supply, but a DC 5V wall plug (something like a cell phone charger) will do the work (check the max. ampere ratings to be high enough for your LEDs).

A starter package depends on what you already have. Some [jumper cables][6] are always good to have, basic tools for electronics as well, e.g. a soldering iron or some [prototyping board][7].

  [1]: https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices
  [2]: https://www.adafruit.com/products/1487
  [3]: https://www.arduino.cc/en/Main/ArduinoBoardDue
  [4]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [5]: https://www.adafruit.com/product/1787
  [6]: http://www.amazon.com/Kalevel®-120pcs-Multicolored-Female-Breadboard/dp/B00M5WLZDW
  [7]: http://www.amazon.com/microtivity-IB401-400-point-Experiment-Breadboard/dp/B004RXKWDQ


body:
## NeoPixels

The strips based on the WS2812 / SK6812 and similar chips, known by some as *NeoPixels*, are clever ways of implementing fully-addressable 24-bit colour LEDs.

One of the clever things is that they only require one data wire, plus power and Gnd, i.e.

* +5V
* Data
* Gnd

The pixel information is sent by precisely timed sequences of 24 bits per pixel. The first pixel "peels off" these 24 bits (ie. 3 x red / green / blue) and then passes the rest on to the next pixel, and so on.

## Libraries

Various people have written libraries to do this for you including:

* [Adafruit library](https://github.com/adafruit/Adafruit_NeoPixel)
* [NeoPixels Revealed: How to (not need to) generate precisely timed signals](http://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/)
* [My own library which uses SPI](http://www.gammon.com.au/forum/?id=13357)

## Power

Each pixel draws around 60 mA at maximum brightness (showing white) so you need to allow for a heavy-duty power supply. Particularly if you have 5m of 144 pixels/m then that is 720 pixels, which would require 43.2 amps!

According to Adafruit:

> To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps.

Even that means you need 14.4 amps for your 720 pixels!

So bear that in mind when sizing your power supply.

## Addressing methods

The Adafruit library (as far as I can tell) holds the pixel information in RAM, and then "dumps" it to the NeoPixels in one operation. This lets you do fancy things in memory, and copy the results to the pixels. However that means you need enough RAM for all this. At 3 bytes per pixel (24 bits), if you have 720 pixels, that will be 2160 bytes, which is more RAM than the smaller processors (like the Uno) have.

Larger processors (like the Mega) have more RAM.

An alternative method, as explained [here](http://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/) does not keep the data in RAM, but generates the colours "procedurally" on-the-fly. This is much less RAM-intensive, but perhaps less flexible. On that page he links to a [YouTube video](https://www.youtube.com/watch?v=I-lR19_kigs) which shows a humble Arduino Duemilanove (similar to a Uno) driving over 1000 pixels!

Procedural generation however can do quite a lot, for example you can set the entire string to a single colour, change that rapidly, or make a rainbow effect by increasing (say) the red value for each successive pixel. You can also make "chaser" effects quite simply.

The [library I wrote](http://www.gammon.com.au/forum/?id=13357) is also designed to allow you to use minimal RAM. You could conceivably add in your own storage scheme, perhaps only storing one byte per pixel, with less bits per colour (eg. 2 bits each for red, green, blue) and that would reduce RAM requirements by a third.

## Cabling run

You could try sending the data over 2m. I warn you that the timing for a zero-bit is that it has to go HIGH and then LOW within about 400 ns, so you can't afford to have the data signal degrade too much.

When I had a similar string of coloured LEDs set up at Xmas time (not NeoPixels however) I had a long run of a 5V power supply (just using a pair of figure-8 wire), and situated the processor quite close to the pixels. This is probably the safest way of doing it.


message:
Servo control using DIP switch

I am pretty new to Arduino and programming too.
I want to sweep a servo using DIP switch. At the moment, I use 4 position DIP switch. To each of the switches, I want to set the number of times the servo has to run. Eg., Pos 1 of DIP switch says, sweep for 5 times. Pos 2 says, sweeps for 10 times etc.

I wrote the following code:

    #include <Servo.h>

    Servo myservo;
    int pos = 0;
    int count = 0;   // might need later
    int runXTimes = 0;

    #define S1 2
    #define S2 3
    #define S3 4
    #define S4 5

    int s1state = HIGH;
    int s2state = HIGH;
    int s3state = HIGH;
    int s4state = HIGH;

    void setup() {
       myservo.attach(9);
       pinMode(S1, INPUT_PULLUP);
       pinMode(S2, INPUT_PULLUP);
       pinMode(S3, INPUT_PULLUP);
       pinMode(S4, INPUT_PULLUP);
       pinMode(9, OUTPUT);
    }

    void loop() {

       s1state = digitalRead(S1);
       s2state = digitalRead(S2);
       s3state = digitalRead(S3);
       s4state = digitalRead(S4);

       // Servo control through Switch 1
       if (s1state == LOW) {     // read the input pin
          for (int runXTimes = 0; runXTimes < 5; runXTimes++) {    // Servo to     sweep for 5 times
             for (pos = 0; pos <= 80; pos += 1)  // goes from 0 degrees to 80 degrees in steps of  degree

             {
                myservo.write(pos);              // tell servo to go to position in variable 'pos'
                delay(5);
             }

             for(pos = 80; pos>=0; pos-=1)     // goes from 80 degrees to 0 degrees
             {
                myservo.write(pos);              // tell servo to go to position in variable 'pos'
                delay(5);
             }

          }

       }

       // Servo control through Switch 2. Used servo detach here
       else if (s2state == LOW) {  // read the input pin
          for (int runXTimes = 0; runXTimes < 10; runXTimes++) {  // Servo to sweep for 10 times
             for (pos = 0; pos <= 80; pos += 1)  // goes from 0 degrees to 80 degrees in steps of  degree
             {
                myservo.write(pos);              // tell servo to go to position in variable 'pos'
                delay(5);
             }

             for(pos = 80; pos>=0; pos-=1)     // goes from 80 degrees to 0 degrees
             {
                myservo.write(pos);              // tell servo to go to position in variable 'pos'
                delay(5);
             }

          }
          myservo.detach();
       }

       // Servo control through Switch 3
       else if (s3state == LOW) {  // read the input pin
          for (pos = 0; pos <= 80; pos += 1)  // goes from 0 degrees to 80 degrees in steps of  degree
          {                                  //
             myservo.write(pos);              // tell servo to go to position in variable 'pos'
             delay(5);
          }

          for(pos = 80; pos>=0; pos-=1)     // goes from 80 degrees to 0 degrees
          {
             myservo.write(pos);              // tell servo to go to position in variable 'pos'
             delay(5);
          }
       }

       // Servo control through Switch 4
       else if (s4state == LOW) {  // read the input pin
          for (pos = 0; pos <= 80; pos += 1)  // goes from 0 degrees to 80 degrees  in steps of  degree
          {
             myservo.write(pos);              // tell servo to go to position in variable 'pos'

             delay(5);
          }

          for(pos = 80; pos>=0; pos-=1)     // goes from 80 degrees to 0 degrees
          {
             myservo.write(pos);              // tell servo to go to position in variable 'pos'
             delay(5);
          }

       }
    }

The actions that happen with the above code are:
1) Servo control through Switch 1 - If I switch ON (0) and then OFF (1) immediately, the servo sweeps for 5 times. Works more like a button switch. If I switch ON and OFF (immediately) again, I am able to sweep 5 times again. But, if I leave the switch in 1, the sweep does not stop after 5 times.
2) Servo control through Switch 2: If I switch ON, the servo sweeps for 10 times and stops as per my interest. But, if I change the switch to 0 and 1 again, the sequence does not start. In fact, no other switch works. I need to power OFF the Arduino to run the program again.
3) Servo control through Switch 3 (= switch 4): If my switch is 1, the servo sweeps. If my switch is 0, the servo stops.

Could you please suggest:
1) How to write the code so that my servo sweeps only for the set number of times even when the switch is in 1 always or whenever I toggle between 0 and 1?
2) I do not want to use serial communication (or typically a PC). Is it possible to interface a 7-segment  or LCD to display the number of sweeps completed or still left.

Thank you in advance.

body:
If you put the sweep-code in the setup function, it would execute once (because setup() is only called once) and you would see what you expected.

But, as it is in the loop() function, it executes each time the loop() function executes - that is the point of the loop() function. As another alternative, you could put an infinite- or forever loop

    for(;;)
       ;    // program hangs here forever

at the end of the loop() function to prevent it returning and getting called again. Either way, you would see a single pass over the steps you coded.


body:
Your switch 2 code includes a myservo.detach() at the end which prevents any further server code from operating.

If you want the switch 1 code to execute only once, you could add a myservo.detach() to the block.

You also seem to want to recycle for the appropriate number of times if you clear the switch.  For this, you may want to myservo.attach(9) when all the switches are open.

Alternately,  you could avoide the detach() and attach() by adding a one-shot flag to the conditionals, set it inside the conditional, and clear it when the switches are clear.

For example:

       if (!s1state & !s2state & !s3state & !s4state) armed = 1;
       ...

       if (armed & s1state == LOW) {     // read the stored input pin value
           armed = 0;
           ...


body:
This is imagination-based since I can't test it myself at this moment, but feel free to ask if something is not right.

    int readswitch()
    {
     int S1,S2,S3,S4;
     uint8_t data = 255;
     data |= digitalRead(S4)<<3;
     data |= digitalRead(S3)<<2;
     data |= digitalRead(S2)<<1;
     data |= digitalRead(S1)<<0;

      if (data==0b11111110) return 1; else
      if (data==0b11111101) return 2; else
      if (data==0b11111011) return 3; else
      if (data==0b11110111) return 4; else
      //add another condition here if you want
      return 0;
    }

    int laststate = 0;
    int state = 0;
    int rotation;

    void setup()
    {
      //setup here, including LCD initialization
      //..
      //..
      //..
    }

    void updateLCD(int x,int y)
    {
      lcd.clear();
      //displaying pin status
      lcd.print("dip : ");
      lcd.print(x,DEC);
      lcd.print(" rot : ");
      lcd.print(y,DEC);
    }

    void loop()
    {
      state = readswitch();
      if (state!=laststate)
      {
        if (state == 1)
        {
          rotation = 5;
          for (int i = 0; i< rotation; i++)
            {
             //update lcd
             updateLCD(state,(rotation-i));

             //.. servo rotation
             //..
            }
          //...
        } else

        if (state == 2)
        {
          //do what you want here if switch 2 == LOW
          //...
        } else

        if (state == 3) //switch 1 == LOW
        {
          //do what you want here if switch 3 == LOW
          //...
        } else

        if (state == 4) //switch 1 == LOW
        {
          //do what you want here if switch 4 == LOW
          //...
        }
      }
      laststate = state;

    }

For more information about LCD, you can refer [to this documentation][1]

  [1]: https://www.arduino.cc/en/Tutorial/LiquidCrystalScroll


message:
Adding Attiny to Arduino IDE - attiny\variants\platform.txt file missing

I followed [this guide][1] to program AtTiny using Arduino as ISP. The problem is that it has some file missing:

    java.io.FileNotFoundException: C:\...\arduino-1.6.8\hardware\attiny\variants\platform.txt

The attiny directory is [clone of this repository][2]. How do I make it work?

  [1]: http://www.instructables.com/id/Programming-an-ATTiny13A-using-Arduino-servo-int/step3/Programming/
  [2]: https://github.com/tekstop/attiny/tree/Arduino1

body:
The way of adding boards has changed in the newer version.

 Try finding a tutorial for 1.6, or download the older [1.0 version](http://arduino.cc/download_handler.php?f=/arduino-1.0.6-windows.exe).


body:
* Open the "Preferences" dialog in the Arduino IDE.

* Click on the symbol next to "Additional Board Manager URLs"

    [![Additional Board Manager URLs][1]][1]

* Paste the following into the box (possibly on a new line under any existing URLs), then click OK.

        https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json

    [![Add board URL][2]][2]

    Note that you can click on the circled link for a list of boards. This will open in your web browser. You may have to switch to your browser to notice it.

[![List of unofficial boards][3]][3]

* Click OK to close the Preferences dialog box.

* In the Tools menu / Board select the Boards Manager:

    [![Boards Manager][4]][4]

* Scroll down until you see the Attiny entry (or the one for the board you want), click on it to select it, and then click "Install".

    [![Install Attiny][5]][5]

* Once done, close the Board Manager dialog box.

* You should now be able to select Attiny from the Boards menu:

    [![Select Attiny][6]][6]

* Now in the Tools menu you can select which Attiny you want to use:

    [![Which Attiny][7]][7]

* Notice you can also select the appropriate clock speed in an adjacent menu item.

* To program the Attiny you will need a suitable ISP (In System Programmer) such as the AVRISP programmer, or the USBtinyISP programmer.

  [1]: https://i.stack.imgur.com/dKgF0.png
  [2]: https://i.stack.imgur.com/LHX4Q.png
  [3]: https://i.stack.imgur.com/JIh4H.png
  [4]: https://i.stack.imgur.com/VuJqY.png
  [5]: https://i.stack.imgur.com/qIRzw.png
  [6]: https://i.stack.imgur.com/7GlZv.png
  [7]: https://i.stack.imgur.com/u64TK.png


message:
How can I easily see which COM port is used by Arduino?

I'm rather disappointed because I just bought arduino and I am unable to upload any projects. The error I get is:

    avrdude: ser_open(): can't open device "\\.\COM3": Časový limit semaforu vypršel.

Can be translated as:

    avrdude: ser_open(): can't open device "\\.\COM3": Semaphore time out

Am I expected to brute-force all available ports to see which one is reserved for arduino? How can I, on Windows 7, quickly determine which port to use given that the IDE for some reason can't do that for me.

body:
Start | Control Panel | System | Device Manager | Ports (COM & LTP).

Watch the list change as you plug / unplug the Arduino. The new port is the Arduino.


body:
You may have to install a device driver. There is a "drivers" directory in the IDE download with some in it.

Example:

[![Windows drivers][1]][1]

According to the readme.txt file:

> With this version of Arduino a new all-in-one driver (with
security signature for Windows 8) is supplied.
>
> The old (deprecated) drivers are still available in the
Old_Arduino_Drivers.zip

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


message:
Where are the chip configurations stored in IDE 1.6.x? How to modify them?

With the new 1.6.x version of the Arduino IDE, obscurity of adding new chips has gained new level. It now seems you have to add HTTP links to some JSON files in single-line edit field in settings.

I did so and to add AtTiny to Arduino IDE, I used this JSON file: https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json

I have AtTiny 13 however. It's same as the others, according to datasheet, but has different signature:

    avrdude: Expected signature for ATtiny45 is 1E 92 06
             Double check chip, or use -F to override this check.
    Wrong microcontroller found.  Did you select the right board from the Tools > Board menu?

I tried to search ATTiny45 and the signature over the files - no success.

What I need is to add the ATTiny13 to the list so that I can finally actually do some programming, instead of being completely helpless.

body:
You are importing a json file provided by someone for free.
The best thing you can do is contribute by adding ATTiny13 to this repository.
To do so:
So go to github (create a account if you do not have one);
create a fork of the repository.
Add your ATTiny13 board to the boards.txt file.
mod the json file to contain a new version and the attiny13.
Test and if everything works fine
Create a pull request


body:
This doesn't answer the original question (which was **how and where to modify the board configurations**) but at least solves the immediate problem.

This repository contains working and maintained profiles for Attiny13: https://github.com/MCUdude/MicroCore


message:
Accelerometer axis inputs driving three RGB LED strips - Trinket Pro 5V

I am looking to take the analogRead Value of the x, y and z axis (at pins 0, 2 and 4) and if it's a motion state, perform a rainbow, cylone and cascade LED sequences using Adafruit Neopixel library.

Using serial connection, I saw that x,y,z axis are read at values of approximately 300.

When I run the code it executed the three Neopixel sequences (redPin at pin 3, GreenPin at pin 5 and BluePin at pin 6) and then continues, even if there is no change of the accelerometer position.

What am I doing wrong?
I am using Arduino Trinket Pro 5V and working with the x-axis and RGB strip at pin 3 only to start.

Thank you for your help.

    #include <Adafruit_NeoPixel.h>
    #include "WS2812_Definitions.h"

    #define PIN1 3
    #define LED_COUNT1 5
    #define PIN2 5
    #define LED_COUNT2 5
    #define PIN3 6
    #define LED_COUNT3 5

    // Create an instance of the Adafruit_NeoPixel class called "leds".
    // That'll be what we refer to from here on...
    Adafruit_NeoPixel RedPin = Adafruit_NeoPixel(LED_COUNT1, PIN1, NEO_GRB + NEO_KHZ800);
    Adafruit_NeoPixel GreenPin = Adafruit_NeoPixel(LED_COUNT2, PIN2, NEO_GRB + NEO_KHZ800);
    Adafruit_NeoPixel BluePin = Adafruit_NeoPixel(LED_COUNT3, PIN3, NEO_GRB + NEO_KHZ800);

    const int sensorPinRed = A0;
    const int sensorPinGreen = A2;
    const int sensorPinBlue = A4;

    int analogValue = 0;

    void setup()
    {

      RedPin.begin();  // Call this to start up the LED strip.
      //GreenPin.begin();
      //BluePin.begin();
      clearLEDs();   // This function, defined below, turns all LEDs off...
      RedPin.show();   // ...but the LEDs don't actually update until you call this.
      //GreenPin.show();
      //BluePin.show()}

    void loop()
    {
      do{
       analogValue = analogRead(sensorPinRed);
      // Ride the Rainbow Road
      for (int i=0; i<LED_COUNT1*10; i++)
      {
        rainbow(i);
        delay(100);  // Delay between rainbow slides
      }

      // Indigo cylon
      // Do a cylon (larson scanner) cycle 10 times
      for (int i=0; i<10; i++)
      {
        // cylon function: first param is color, second is time (in ms) between cycles
        cylon(INDIGO, 500);  // Indigo cylon eye!
      }

      // A light shower of spring green rain
      // This will run the cascade from top->bottom 20 times
      for (int i=0; i<20; i++)
      {
        // First parameter is the color, second is direction, third is ms between falls
        cascade(MEDIUMSPRINGGREEN, TOP_DOWN, 100);
      }
      } while (analogValue>300);
    }

    // Implements a little larson "cylon" sanner.
    // This'll run one full cycle, down one way and back the other
    void cylon(unsigned long color, byte wait)
    {
      // weight determines how much lighter the outer "eye" colors are
      const byte weight = 4;
      // It'll be easier to decrement each of these colors individually
      // so we'll split them out of the 24-bit color value
      byte red = (color & 0xFF0000) >> 16;
      byte green = (color & 0x00FF00) >> 8;
      byte blue = (color & 0x0000FF);

      // Start at closest LED, and move to the outside
      for (int i=0; i<=LED_COUNT1-1; i++)
      {
        clearLEDs();
        RedPin.setPixelColor(i, red, green, blue);  // Set the bright middle eye
        // Now set two eyes to each side to get progressively dimmer
        for (int j=1; j<3; j++)
        {
          if (i-j >= 0)
            RedPin.setPixelColor(i-j, red/(weight*j), green/(weight*j), blue/(weight*j));
          if (i-j <= LED_COUNT1)
            RedPin.setPixelColor(i+j, red/(weight*j), green/(weight*j), blue/(weight*j));
        }
        RedPin.show();  // Turn the LEDs on
        delay(wait);  // Delay for visibility
      }

      // Now we go back to where we came. Do the same thing.
      for (int i=LED_COUNT1-2; i>=1; i--)
      {
        clearLEDs();
        RedPin.setPixelColor(i, red, green, blue);
        for (int j=1; j<3; j++)
        {
          if (i-j >= 0)
            RedPin.setPixelColor(i-j, red/(weight*j), green/(weight*j), blue/(weight*j));
          if (i-j <= LED_COUNT1)
            RedPin.setPixelColor(i+j, red/(weight*j), green/(weight*j), blue/(weight*j));
          }

        RedPin.show();
        delay(wait);
      }
    }

    // Cascades a single direction. One time.
    void cascade(unsigned long color, byte direction, byte wait)
    {
      if (direction == TOP_DOWN)
      {
        for (int i=0; i<LED_COUNT1; i++)
        {
          clearLEDs();  // Turn off all LEDs
          RedPin.setPixelColor(i, color);  // Set just this one
          RedPin.show();
          delay(wait);
        }
      }
      else
      {
        for (int i=LED_COUNT1-1; i>=0; i--)
        {
          clearLEDs();
          RedPin.setPixelColor(i, color);
          RedPin.show();
          delay(wait);
        }
      }
    }

    // Sets all LEDs to off, but DOES NOT update the display;
    // call leds.show() to actually turn them off after this.
    void clearLEDs()
    {
      for (int i=0; i<LED_COUNT1; i++)
      {
        RedPin.setPixelColor(i, 0);
      }
    }

    // Prints a rainbow on the ENTIRE LED strip.
    //  The rainbow begins at a specified position.
    // ROY G BIV!
    void rainbow(byte startPosition)
    {
      // Need to scale our rainbow. We want a variety of colors, even if there
      // are just 10 or so pixels.
      int rainbowScale = 192 / LED_COUNT1;

      // Next we setup each pixel with the right color
      for (int i=0; i<LED_COUNT1; i++)
      {
        // There are 192 total colors we can get out of the rainbowOrder function.
        // It'll return a color between red->orange->green->...->violet for 0-191.
        RedPin.setPixelColor(i, rainbowOrder((rainbowScale * (i + startPosition)) % 192));
      }
      // Finally, actually turn the LEDs on:
      RedPin.show();
    }

body:
It seems to me that you are coding to always display something on the LEDs:

<!-- language-all: lang-C++ -->

      void loop()
      {
        do {
          analogValue = analogRead(sensorPinRed);
          // display stuff
        } while (analogValue > 300);
      }

Assuming that you want the LEDs off when `analogValue` is <= 300, you have the test in the wrong place. That always does the loop at least once. How about:

      void loop()
        {
        analogValue = analogRead(sensorPinRed);
        if (analogValue > 300)
          {
          // display stuff
          }
        else
          {
          clearLEDs();   // Turn all LEDs off...
          RedPin.show();
          BluePin.show();
          GreenPin.show();
          }
        }


body:
Thanks to @nick-gammon for debugging my code.

I cleaned it up so below is the working sample. X-axis of the accelerometer is related to PWM pin 3 RGB LED strip, Y axis of pin 5 and Z axis to pin 6.

The LED sequence cascades once in spring green color in response to the tilt in direction.

<!-- language-all: lang-C++ -->

    #include <Adafruit_NeoPixel.h>
    #include "WS2812_Definitions.h"

    #define PIN1 3
    #define LED_COUNT1 5
    #define PIN2 5
    #define LED_COUNT2 5
    #define PIN3 6
    #define LED_COUNT3 5

    // Create an instance of the Adafruit_NeoPixel class called "XPin", "YPin" and "ZPin".
    // That'll be what we refer to from here on...
    Adafruit_NeoPixel XPin = Adafruit_NeoPixel(LED_COUNT1, PIN1, NEO_GRB + NEO_KHZ800);
    Adafruit_NeoPixel YPin = Adafruit_NeoPixel(LED_COUNT2, PIN2, NEO_GRB + NEO_KHZ800);
    Adafruit_NeoPixel ZPin = Adafruit_NeoPixel(LED_COUNT3, PIN3, NEO_GRB + NEO_KHZ800);

    const int sensorPinX = A0;
    const int sensorPinY = A2;
    const int sensorPinZ = A4;

    int analogValueX = 0;
    int analogValueY = 0;
    int analogValueZ = 0;

    void setup()
    {

      XPin.begin();  // Call this to start up the LED strip.
      YPin.begin();
      ZPin.begin();
      clearLEDs();   // This function, defined below, turns all LEDs off...

    }

    void loop()
    {
       analogValueX = analogRead(sensorPinX);
       analogValueY = analogRead(sensorPinY);
       analogValueZ = analogRead(sensorPinZ);
       if ((analogValueX > 400) || (analogValueY > 400) || (analogValueZ > 400) )
       {

      // A light shower of spring green rain
      // This will run the cascade from top->bottom i times
      for (int i=0; i<1; i++)
      {
        // First parameter is the color, second is direction, third is ms between falls
        cascade(MEDIUMSPRINGGREEN, TOP_DOWN, 100);
      }
       }
       else
       {
         clearLEDs(); // Turn all LEDs off
       }
    }

    // Cascades a single direction. One time.
    void cascade(unsigned long color, byte direction, byte wait)
    {
      if (direction == TOP_DOWN)
      {
        for (int i=0; i<LED_COUNT1; i++)
        {
          clearLEDs();  // Turn off all LEDs
          XPin.setPixelColor(i, color);  // Set just this one
          XPin.show();
          delay(wait);
        }

        for (int i=0; i<LED_COUNT2; i++)
        {
          clearLEDs();  // Turn off all LEDs
          YPin.setPixelColor(i, color);  // Set just this one
          YPin.show();
          delay(wait);
        }
        for (int i=0; i<LED_COUNT3; i++)
        {
          clearLEDs();  // Turn off all LEDs
          ZPin.setPixelColor(i, color);  // Set just this one
          ZPin.show();
          delay(wait);
        }
      }
      else
      {
        for (int i=LED_COUNT1-1; i>=0; i--)
        {
          clearLEDs();
          XPin.setPixelColor(i, color);
          XPin.show();
          delay(wait);
        }

        for (int i=LED_COUNT2-1; i>=0; i--)
        {
          clearLEDs();
          YPin.setPixelColor(i, color);
          YPin.show();
          delay(wait);
        }

        for (int i=LED_COUNT3-1; i>=0; i--)
        {
          clearLEDs();
          ZPin.setPixelColor(i, color);
          ZPin.show();
          delay(wait);
        }
      }
    }

    // Sets all LEDs to off, but DOES NOT update the display;
    // call leds.show() to actually turn them off after this.
    void clearLEDs()
    {
      for (int i=0; i<LED_COUNT1; i++)
      {
        XPin.setPixelColor(i, 0);
      }
      for (int i=0; i<LED_COUNT2; i++)
      {
        YPin.setPixelColor(i, 0);
      }
      for (int i=0; i<LED_COUNT3; i++)
      {
        ZPin.setPixelColor(i, 0);
      }
    }


message:
Timer to control 1.5V clock

I want to make either an alarm clock or countdown timer whose alarm is loud enough to notice, but soft enough to not wake me up when asleep. My idea is to use the sound of an analog clock that I have - powered by a single AA 1.5V battery. I like this sound. So, I'd like to create an alarm or a timer that can turn on the power to this analog clock for a few minutes at least. Ideally, it would be something I could use daily for a couple hours without replacing the timer/alarm battery too often.

I've looked at these programmable relay timers: http://www.amazon.com/dp/B00P0TZ5CY/ but the voltage seems kindof overkill.

I've also considered an arduino board, but I'd like to be able to set the time on the device without plugging it into a computer.

I'm a developer, so I could do arduino programming if needed, but I don't know much about circuitry & hardware. I've also never done an arduino project, so I'm starting from 101.

Any ideas where I could start? The timer I mentioned above would be perfect if it didn't require 12V power. My knowledge is limited, so maybe that's less of a big deal than I think.

body:
I suggest a simple setup (similar to my [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) but less complex).

You can run from 3 x AA batteries, and have an RTC clock to keep track of the time. You can use a MOSFET to turn on your analog clock when required.

The processor can be asleep most of the time, using the watchdog timer to wake up and check the time from the RTC. Don't use an Arduino "board" unless you are running from a wall-wart because the voltage regulator, USB interface, and power LED, will consume too much power.


message:
Append Text to Variable Names: Please Help Me Shorten This Code

I'm trying to shorten the code under "setup" below, where I have over 120 variables that are being read from an external EEPROM. There is a pattern where the variable that stores the position of the EEPROM address is the name of the variable being populated, plus the word "Pos".

    byte fanSpeed, nl1Toggle, ledsToggle;
    byte fanSpeedPos = 12, nl1TogglePos = 95, ledsTogglePos = 7;

    void setup() {
      fanSpeed = readEE(fanSpeedPos);
      nl1Toggle = readEE(nl1TogglePos);
      ledsToggle = readEE(ledsTogglePos);
      //there are over 120 of the above readEE statements in the actual code.
    }

    uint8_t readEE(uint8_t entry) {
      readEEPROM(AT24C32_ADDRESS, 1, entry);
    }

Ideally I would like it to work like this (I'm using pseudo code because I don't know how to do this):

    char* variableNames [] = { "fanSpeed", "nl1Toggle", "ledsToggle" };
    byte fanSpeedPos = 12, nl1TogglePos = 95, ledsTogglePos = 7;

    void setup() {
      for (int i = 1; i < 120; i++;) {
        variableNames[i] = readEE(variableNames[i] + 'Pos');
      }

Is this possible using C++ / Arduino?

body:
    variableNames[i] = readEE(variableNames[i] + 'Pos');

> Is this possible using C++ / Arduino?

No! Very few programming languages allow that as it requires a lot of run-time information.

Let us instead revisit you issue; Load a large set of variables from [EEPROM][1]. What mechanisms do we have in C/C++ and AVR library that could help with this?

Here is a really simple solution that results in a "one-liner"; eeprom_read_block().

    struct var_t {
      byte fanSpeed, nl1Toggle, ledsToggle;
    };
    var_t var;
    const void* pos = ...;
    eeprom_read_block(&var, pos, sizeof(var));

Obviously `var_t` and `var` are not very good names (and you will have to come up with something better) and this is for the internal EEPROM but the same technique can be used for the I2C EEPROM.

Cheers!

BW: What AT24CXXX library are you using? Because this looks strange.

     uint8_t readEE(uint8_t entry) {
       readEEPROM(AT24C32_ADDRESS, 1, entry);
     }

No return statement, etc.

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html
  [2]: https://github.com/kriswiner/DS3231RTC/blob/master/DS3231RTCBasicExample.ino#L428


body:
This can be achieved with a simple preprocessor macro:

    #define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)

You can then use:

    readEE(foo);

and it will be expanded out to:

    foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);

The `##` operator in macros expands out both sides (VAR and Pos) and then concatenates the results together. Since VAR itself is a macro (whatever you pass when you call the macro) it gets replaced with that value, but Pos, because it isn't a macro, just stays as Pos. So you end up with your variable name concatenated with the word Pos.

Note that you can't use that in a loop with variable names in an array - simply because variable names only exist in the source code, not in the compiled code, so you can't do anything with those variable names once the code is compiled.  Hence you have to use the preprocessor to do the job.

Yes, it means you still have to write 120 lines of code for all 120 variables, but they are just shortened to `readEE(varname);`.

However a better solution is to either use Mikael's struct method, or to just use an array and think differently about the concept of names:

    uint8_t data[120];
    for (int i = 0; i < 120; i++) {
        data[i] = readEEPROM(AT24C32_ADDRESS, 1, i);
    );

So now all your variable values are in the `data[]` array, and you just need to know, in your program, which value is which - and you can do that by defining names for each position as preprocessor macros:

    #define FAN_SPEED 12
    #define N1_TOGGLE 95
    #define LEDS_TOGGLE 7

Then use those macros in place of the numbers:

    Serial.println(data[FAN_SPEED]);

Alternatively you could use the macros to "mask" variable names:

    #define fanSpeed data[12]
    #define n1Toggle data[95]
    #define ledsToggle data[7]

There is one thing you might have noticed though: Nothing here shortens your code, it just moves things around a bit. Let's face it - you have 120 variables stored in 120 locations. Whatever you do you're still going to have to have 120 pointers of some form to those variables and their locations. All you can really do is choose the method that provides the most readability so that someone else looking at your code can understand what is going on. Whatever you do you have a long list of variables or variable names to define or set up, which means a lot of typing.


message:
Arduino Uno not working as usb HID interface

I have an arduino uno rev 3 and it works perfectly fine. I the OS I am using is Kali Linux 2.0 and you can upload everything as normal to the arduino.
I am following this tutorial:[Arduino Uno as usb HID interface device][1]
to use my arduino uno r3 as a hid device. After I upload the

    Arduino-keyboard-0.3.hex

file, I plug cycle the board and I try uploading the example blink program. It always says:

    Serial Port /dev/ttyACM0 not found.
    Retry the upload with another serial port?
    /dev/ttyS0
the /dev/ttyACM0 is my default arduino port and /dev/ttyS0 is one of my usb devices that is plugged in. Neverless, I tried uploading but it says board isnt responding. Can someone help me with this please?

  [1]: http://www.kevindemarco.com/2014/01/02/arduino-uno-as-a-usb-hid-interface/

body:
You have reprogrammed the ATMega16U2 chip to be a HID device. Thus it no longer functions as a serial interface between the Atmega328P and your computer. You need to reflash the firmware on the ATMega16U2 to return to normal operation.

I have instructions for how you might to this on my [bootloader uploader](http://www.gammon.com.au/bootloader) page. In brief, you need to put the original hex file back:

    sudo dfu-programmer atmega16u2 flash Arduino-atmega16u2-Uno-firmware-Rev3.hex

There are other ways of turning your Uno into a HID device. Search for "Virtual USB Arduino".

More easily, get a Arduino Leonardo or Arduino Micro which are designed for this sort of thing.

---

> Yes but how can I use **it** as a HID? ...  it cannot detect **it** so how would I be able to upload code to **it**  ...

What is "it" here? Look at this photo:

[![Uno from above][1]][1]

There are two processors on the Uno. It sounds like you have reflashed the ATMega16U2. Do you want to use the ATMega16U2 as a HID or the Atmega328P as a HID? They need totally different techniques.

Once you reflash the ATMega16U2 you can't "get to" the Atmega328P via the USB interface.

On the page you linked there is a workflow for programming the ATMega16U2. Are you following it? If so, which part is not working for you? If not, why not?

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


message:
How to program pressure sensor and motor with motor shield

I was working on controlling a high power motor with a heavy duty motor controller, and I was able to make my motor spin, but I wasn't able to incorporate a program for my pressure sensor and make it determine the speed of the motor.  I'm pretty sure I connected the parts correctly on my circuit board, so I figure my code must have some mistake, or something missing.
The pressure sensor I'm using:
The motor controller I'm using: http://www.robotshop.com/en/arduino-compatible-mega-motor-shield-1a-5-28v.html#Useful
The code I have:

<!-- language: c -->

    int motorValue=0;
    int sensorValue=0;
    int sensorPin=A0;
    int EnablePin=8;
    int PWMPin2=3;

    void setup() {
      // put your setup code here, to run once:
    pinMode(EnablePin, OUTPUT);
    //pinMode(sensorPin, OUTPUT);
    Serial.begin(9600);
    pinMode(PWMPin2, OUTPUT);
    pinMode(sensorPin, INPUT);
    }

    void loop() {
    // put your main code here, to run repeatedly:
    sensorValue = analogRead(sensorPin);

    //float voltage = sensorValue * (5.0 / 1023.0);

    //Serial.println(voltage);

    delay(50);

    motorValue=map(sensorValue,0,1023,0,255);
    //motorValue=sensorValue / 4;
    //analogWrite(motorPin,motorValue);
    digitalWrite(EnablePin, HIGH);
    analogWrite(PWMPin2, motorValue);
    }

Edit: The sensor works by reading the voltage.  Here's an actual picture of how I wired it: [![Here's how I wired it][1]][1] I used this wiring to print out the voltage with just the Arduino and it worked, and I'm using it with the same wiring but while having the motor shield on top, so that's why I'm guessing that I must not be programming the sensor right with the motor controller.  I couldn't get the voltage readings when I used this setup with the motor driver shield.

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

body:
Depending on the jumper settings, the MegaMoto shield will drive current sense voltages onto one or two of the Arduino analog inputs.

Your picture shows the shunt installed to drive A0, which is of course going to conflict with your attempt to use the same pin for the force sensor.

If you are not using current feedback, it seems like you may be able to just remove that jumper, otherwise you will need to pick distinct pins for the current sense and your force sensor.  Consult the manual to be certain.

(The other placement of the other jumper in that block looks a bit suspicious too, almost seems it may be shorting the two current sense channels together, but not certain about that)


message:
SOLVED -- Switch PIN, Also Trigger Other Pin in Arduino

I would like to know.

I have Pin 6, 7, 8 and 9 as INPUT_PULLUP. I have switch to each other pin. Why when I press switch at PIN 6. **SOMETIMES** PIN 7 also getting input. Other case, also when I press switch at 7, other pin also trigger. Why?

This case is random. Sometimes everything is ok when I press 10 times, but after that other pin also trigger. Another case only 4-5 times press, then other pin also trigger.

I use switch on/off not temporary switch.

How to fix this? Is it common problem with arduino?

**UPDATE**

Program. (Simple Program)

    int led1 = 1;
    int led2 = 2;
    int led3 = 3;
    int led4 = 5;

    int switch1 = 6;
    int switch2 = 7;
    int switch3 = 8;
    int switch4 = 9;

    int led = 13;

    //int counter = 0;

    void setup()
    {
      // put your setup code here, to run once
       pinMode(led1, OUTPUT);
          pinMode(led2, OUTPUT);
          pinMode(led3, OUTPUT);
          pinMode(led4, OUTPUT);
          pinMode(switch1, INPUT_PULLUP);
          pinMode(switch2, INPUT_PULLUP);
          pinMode(switch3, INPUT_PULLUP);
          pinMode(switch4, INPUT_PULLUP);
          pinMode(led, OUTPUT);
    }
    void loop()
    {

    if (digitalRead(switch1) == 0){
      digitalWrite(led1, HIGH);
      }

     if (digitalRead(switch1) == 1){
      digitalWrite(led1, LOW);
      }

    if (digitalRead(switch2) == 0){
      digitalWrite(led2, HIGH);
      }

     if (digitalRead(switch2) == 1){
      digitalWrite(led2, LOW);
      }

    if (digitalRead(switch3) == 0){
      digitalWrite(led3, HIGH);
      }

     if (digitalRead(switch3) == 1){
      digitalWrite(led3, LOW);
      }

    if (digitalRead(switch4) == 0){
      digitalWrite(led4, HIGH);
      }

     if (digitalRead(switch4) == 1){
      digitalWrite(led4, LOW);
      }

    digitalWrite(led, HIGH);

    delay(1000);

    digitalWrite(led, LOW);

    }

**Schematic**

[![][1]][1]

My Circuit is simple as like that for the input. For the output only to led, resistor and ground.

I found similar case http://www.instructables.com/id/Arduino-Push-Switch-Debouncing-Interrupts/

>  On the website, He said, "The problem with this setup was when the
> button was pressed the interrupt was being called multiple times and
> even toggling other buttons. Why was this happening? It is caused from
> a switch bouncing feedback."

Is there any solution without modifying the hardware?

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

**SOLVE**

The problem is the wire.

My wire for switch is jumper cable, and each other closer (touch) to each other cable. I try to separate, and works. There is no other pin will be trigger.

body:
You may be getting switching noise between the button wires, which is low-level and brief, but with no debouncing, it could be just enough to cause the effect you're seeing.

I'd suggest 1) writing a short function that [debounces][1] and reads any button; and 2) using if/else statements instead of testing each button twice.

A quick test is to hold one pair of wires closer together or farther apart from each other while you press one of those two buttons, and see whether the distance apart changes the effect. If it does, you've found the cause.

  [1]: http://gammon.com.au/switches


message:
Strange results trying to count pulses

I am now hopelessly stuck and need help please.

I am building an automated observatory and now at the stage of trying to control the observatory dome rotation. The dome is rotated using a step motor and it works fine. The rotation of the dome also turns a rotary encoder to give an independent verification that the dome is moving. Although the RE is a quadrature type I am simply counting RE ticks from both channels as I don't need direction information.

What I am trying to do now is to count how many motor driving pulses occur between each pair of RE ticks. The reasoning behind this is to monitor the dome movements and detect jamming. The actual motor pulses will be used for all dome position calculations.

To achieve this, I have built a small board with a ULN2803A inverting buffer and an Arduino Nano. The Nano uses Pin Change interrupts on pins D11 and D12 to count the RE ticks. Pin D7 will also be used to monitor a Home Position sensor although this doesn't exist at present. The motor pulses are sent via the buffer to Pin D2 (INT0) and the motor direction is sent via the buffer to pin D3 (INT1). The external interrupts are then used to count the motor pulses, up or down depending on the motor direction.

For information, there is another board present, a Velleman VM110 USB breakout board, that also receives the rotary encoder ticks. This gives me a simple way to check that my board gives the same answer when I rotate the rotary encoder shaft by hand.

OK - sorry this is so long winded but now it gets weird.

When I rotate the RE without the motor running everything is fine. I get four times as many pulses as the Velleman board as I am using Pin Changes, triggering on each rise and fall, not on full cycles of the encoder. This does happen as predicted and everything is nice and stable.

BUT - when I start the motor running, I get hundreds of RE ticks every time I move the encoder and sometimes I get increasing RE ticks without touching the encoder at all.

The obvious answer is some form of RFI but I have done everything I can to eliminate this. The motor driver and the Nano board that powers it are in a shielded enclosure, the cable to the motor is a shielded cable and I have 10uH chokes on each of the four motor leads. Finally, I have fitted a filter to the incoming power supply to the motor box to minimise any RFI going back down the power lines.

The use of the ULN2803A buffer was my latest attempt to make this work. Previously the signals went direct to the Nano pins. With the buffer, I have used 20k pull-ups on the input side and 10k pull-ups on the outputs. This was a direct copy of the Velleman board input circuit that I knew worked without problems.

I have looked at the motor pulses at the input pin to the Nano on my scope and they are nice looking, sharp edged pulses of duration 70 uS and a frequency of 497 Hz. Not bad as I set the pulse rate using the Accelstepper library to 500Hz.

I now suspect that this is a software problem. This wouldn't surprise me as I am very new to all this, just trying to learn enough at each stage to do what I need. I have attached the code - this is a stripped down version without a lot of I2C stuff that is not relevant to my problems.

Again, for information. I have tried using the `attachInterrupt()` function and by directly setting the relevant registers - no difference!

Anyway, I really really hope someone can help me sort this out.

Regards, Hugh

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

    /*
    ABoard3
    ROTATION MONITORING AND POSITION
    Version AB3_stripped
    *****************************PURPOSE*****************************************
    This sketch is used on an Arduino Nano to count the motor pulses from ABoard1
    and the Rotary Encoder ticks. The motor pulse count between encoder ticks is
    used to detect dome jamming.
    ****************************INPUTS*******************************************
    PIN CHANGE INTERRUPTS
    **********ROTARY ENCODER INPUT*********
    The rotary encoder is a Bourns ENA1J-B28 L00064L 1139M MEX 64 cycle per turn
    optical encoder. This is connected to ABoard3 Pins D11 and D12. These pins
    connect to Channel A and Channel B respectively. Pin change interrupts are used
    to receive the rotary encoder output.
    (The output pulses from the rotary encoder is also sent to the Velleman board
    for use by LesveDomeNet for finding dome position)
    *********HOME POSITION INPUT*********
    The home position sensor is an Omron EESX671 Optical Sensor.
    The sensor output is connected to ABoard3 Pin D7.
    Pin change interrupt PCINT21 records activation/deactivation of the sensor.
    EXTERNAL INTERRUPTS
    *********MOTOR PULSE INPUT***********
    The pulses sent to the G251X stepper driver are also sent to Aboard3 Pin D2.
    This pin is the External Interrupt pin, vector INT0
    *********MOTOR DIRECTION INPUT********
    Motor direction is input to ABoard3 from ABoard2. ABoard2 pin, pnVmInRotMotor
    (AB2:A0{54}) is connected to Velleman pins DI4 and DO2 and also to AB3:D3.
    AB3:D3 is an External Interrupt pin, vector INT1.
    */

    #include <Wire.h>
    #include "streaming.h"
    #include "I2C_AnythingHEG.h"
    #include <EEPROMex.h>

    //CONSTANTS
    //PIN ASSIGNMENTS For ABOARD3
    const uint8_t pnMotorPulse = 2;      //Port PD2, INT0, ISR(INT0_vect){}
    const uint8_t pnMotorDirection = 3;  //Port PD3, INT1, ISR(INT1_vect){}
    const uint8_t pnDomeAtHome = 7;      //Port PD7, PCINT23,ISR(PCINT2_vect){}
    const uint8_t pnREChanA = 11;        //Port PB3, PCINT3, ISR(PCINT0_vect){}
    const uint8_t pnREChanB = 12;        //Port PB4, PCINT4, ISR(PCINT0_vect){}

    //*****************EXPERIMENTAL STUFF FOR PULSE COUNTING*******************************
    uint16_t volatile myTest = 0;
    int32_t volatile ratioCount = 0L;
    int32_t volatile totalCount = 0L;
    int32_t volatile tickCount = 0L;
    uint8_t volatile halftickCount = 0;
    int32_t volatile addPulse = 0L;

    void setup() {
      //**********************************SERIAL FOR DEBUG ONLY************************
      Serial.begin(115200);
      //*************************INPUT PIN MODE SETUP**********************************
      //NOTE Set all UNUSED PCINT0:5 pins (D8, D9, D10, D11) to OUTPUT.
      //and set the value to LOW
      //The actual pins used to receive interrupts have external 10k pull-ups.
      //This is to reduce susceptibility to interference causing false triggering.
      pinMode(pnMotorPulse, INPUT); //D2
      pinMode(pnMotorDirection, INPUT); //D3
      pinMode(pnDomeAtHome, INPUT); //D7
      pinMode(pnREChanA, INPUT); //D11
      pinMode(pnREChanB, INPUT); //D12
      pinMode(4, OUTPUT); //D4
      digitalWrite(4, LOW);
      pinMode(8, OUTPUT); //D8
      digitalWrite(8, LOW);
      pinMode(9, OUTPUT); //D9
      digitalWrite(9, LOW);
      pinMode(10, OUTPUT); //D10
      digitalWrite(10, LOW);
      //******************SET UP AddPulse According to Motor Direction******************
      //This is needed to make sure the pulse counting starts in the correct direction
      //as the direction is only checked in the ISR after a change has occurred.
      //If Motor Direction is AntiClockwise, change to Subtract a pulse
      if( digitalRead(pnMotorDirection)) {
        addPulse = 1L;
      } else {
        addPulse = -1L;
      }
      //**************************SET UP PIN CHANGE INTERRUPTS**************************
      //Set the Pin Change Interrupt Masks
      //Clear all bits to start with
      PCMSK0 &= 0b00000000; //Clear all bits
      PCMSK1 &= 0b00000000; //Clear all bits
      PCMSK2 &= 0b00000000; //Clear all bits
      //Mask for PCINTs 0 through 7 is PCMSK0 (Rotary Encoder Pulses)
      //Need to allow interrupts on PCINT3 and PCINT4, so set bits 3 and 4
      //PCINT3 is Nano  pin D11 and PCINT4 is Nano pin D12
      //Use a compound bitwise OR to set the bits
      PCMSK0 |= 0b00011000; //Enable PCINT3 ONLY (bit 3)
      //Interrupt on pins 11 and 12, RE Ticks
      //Mask for PCINTs 16through 23 is PCMSK2 (Home Position)
      //Need to allow interrupts on PCINT23 so set bit 7
      PCMSK2 |= 0b10000000; //Interrupt on pin 7, Home Position Sensor activated
      //Now enable the interrupts (TURN THEM ON) by setting bits in PCICR
      //PCICR is Pin Change Interupt Control Register.Set bit 0 (PCIE0)
      //to enable interrupts PCINT0:7 This catches PCINT3 and 4 - RE Ticks
      //Set bit 2 (PCIE2) to enable interrupts PCINT16:23. Catches PCINT21 - Home Position Sensor
      PCICR &= 0b00000000; //Clear PCICR register
      PCICR |= 0b00000001; //Set bit 0 - Catches PCINT3 & PCINT4 - RE Ticks
      PCICR |= 0b00000100; //Set bit 2 - Catch PCINT21 - Home Position Sensor
      //**************************SET UP 'EXTERNAL INTERRUPTS'**************************
      //Interupts on External Interrupt Pins D2 (INT0) and D3 (INT1).
      //INT0 (Nano pin D2)occurs when a stepper motor driver pulse is received
      //INT1 (Nano pin D3)occurs when the ABoard2 pin, pnVmInRotMotor toggles
      //indicating a motor direction change.
      //To use the 'External Interrupts' the following registers need to be set-up:
      //EICRA External Interrupt Control Register A
      //Need to set Interrupt Sense Control bits ISC11 .. ISC00 (bits 3:0 in EICRA)
      //ISC01     ISC00 (INT0)    Interrupt
      //ISC11     ISC01 (INT1)    Generated by
      //  0         0             Low level on Pin
      //  0         1             Any Logical Change
      //  1         0             Falling Edge
      //  1         1             Rising Edge
      //First clear all bits, then set as follows:
      //For INT1 - Motor Direction - Generate on ANY LOGICAL CHANGE
      //bit 3 ISC11 0
      //bit 2 ISC10 1 This combination = Any logical change causes interrupt
      //For INT0 - Stepper Motor Pulses  - Generate on RISING EDGE
      //bit 1 ISC01 1
      //bit 0 ISC00 1 This combination = Rising edge of pulse causes interrupt
      //NOTE: To provide some immunity to RFI, Aboard3:Pins 2 & 3 are pulled high
      //using 10k resistors.
      //So, code is
      EICRA &= 0b00000000; //Clear EICRA register
      EICRA |= 0b00000111; // Set bits 0,1 and 2 in EICRA register
      //EIMSK External Interrupt Mask Register
      //Need to set External Interrupt Request Enables INT1 & INT0  (bits 1:0)
      //First clear both bits, then set as follows:
      //bit 1  INT1  1 External interrupt pin (D3) enabled
      //bit 0  INT0  1 External interrupt pin (D2) enabled
      //So, code is
      EIMSK &= 0b00000000; //Clear EIMSK register
      EIMSK |= 0b00000011; // Set bits 0 and 1 in EIMSK register
      //NOTE: Setting EIMSK TURNS ON THE EXTERNAL INTERRUPTS
      //************VARIABLE INITIALISATION*********
      myCommand = 0;
      myTest = 0;
      tickCount = 0L;
      totalCount = 0L;
    } //END of setup

    void loop() {
      //******************************COMMAND ACTIONS******************************
      if (myTest == 3) (
        //RE tick
        Serial << "Tick Count = " << tickCount << "  totalCount = " << totalCount << "\n";
        myTest = 0;
      }
    }
    //*************************FUNCTIONS / ISRs FROM HEREON*************************
    ISR(INT0_vect) {
      //Triggered by stepper motor drive pulse from ABoard1
      totalCount = totalCount + addPulse;
    }
    ISR(INT1_vect) {
      //Triggered by a change in motor direction
      if(digitalRead(pnMotorDirection)) {
        addPulse = 1L;
      } else {
        addPulse = -1L;
      }
    }
    ISR(PCINT0_vect) {
      //Triggered by a ROTARY ENCODER TICK
      halftickCount++;
      if (halftickCount == 2) {
        //Make count same as Velleman
        tickCount++;
        halftickCount = 0;
        myTest = 3;
      }
    }
    ISR(PCINT2_vect) {
      //Triggered by activation of Home Position Sensor
      myTest = 4;
    }

body:
There is no need to use int32_t for some of the variables. The problem with using variables that are more than 8 bits on a 8-bit processor, is that the processor needs 4 reads to get the value. In the middle of those reads an interrupt might occur, resulting in a value that has some bits of the old value, and some bits of the new.

Some variable only need 8 bits.

    uint8_t volatile myTest = 0;
    int32_t volatile totalCount = 0L;
    int32_t volatile tickCount = 0L;
    uint8_t volatile halftickCount = 0;
    int8_t volatile addPulse = 0L;

The next thing is to make the reading of the value atomic.

    void loop()
    {
    //******************************COMMAND ACTIONS******************************

    if (myTest == 3)   //RE tick
    {
        noInterrupts();
        int32_t tickCountCopy = tickCount;
        int32_t totalCountCopy = totalCount;
        interrupts();
        Serial << "Tick Count = " << tickCountCopy << "  totalCount = " << totalCountCopy << "\n";
        myTest = 0;
    }
    }

PS. this is not necessarily an answer, but it didn't fit in the comments.


message:
ATMEL SAMD11 SPI (Slave) With Arduino (Master)

I am trying to get my Atmel SAMD11 XPLAINED PRO and arduino to talk to each other using SPI. I have set up the arduino as the master, with the SAMD11 as the slave. On the ATMEL, I have the following code:

http://asf.atmel.com/docs/latest/samd21/html/asfdoc_sam0_sercom_spi_slave_callback_use.html

Essentially, it waits until the master sends data, compares the data with what it expects, and updates an LED accordingly. On the arduino side, I have the following:

    #include <SPI.h>

    #define BUF_LENGTH 20
    int slave_select = 10;

    void setup (void)
    {
      // Initialize serial for DEBUG.
      Serial.begin(9600);
      pinMode (slave_select, OUTPUT);
      digitalWrite(slave_select, HIGH);  // ensure SS stays high for now
      // Put SCK, MOSI, SS pins into output mode
      // also put SCK, MOSI into LOW state, and SS into HIGH state.
      // Then put SPI hardware into Master mode and turn SPI on
      SPI.beginTransaction (SPISettings (4000000, MSBFIRST, SPI_MODE0));  // 4 MHz clock, MSB first, mode 0
      // Master initialized.
      Serial.println("Master Initialized");
    }  // end of setup

    void loop (void)
    {
      static uint8_t buffer_expect[BUF_LENGTH] = {
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
         0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13
      };
      // enable Slave Select
      digitalWrite(slave_select, LOW);    // SS is pin 10

      //write the 20 bytes
      for (int I=0;I<20;I++)
      {
        SPI.transfer(buffer_expect[I]); //write data byte
        delay(20);
      }

      // disable Slave Select
      digitalWrite(slave_select, HIGH);

      delay (1000);  // 1 seconds delay
    }  // end of loop

When I run the code, the LED on the SAMD11 isn't updated, which means that it is waiting for data to be sent, and hasn't received any, despite what the arduino code writes. On the hardware side, I have GND connected on both boards, VCC on the SAM to 5V on the arduino, and SPI_SS_A, MOSI, MISO and SCK connected to pins 10,11,12 and 13 on the arduino respectively.

body:
You haven't set your SS pin as an output anywhere in your code.

The arduino page you linked to has a note near the bottom which reads:

> Note about Slave Select (SS) pin on AVR based boards
>
> All AVR based boards have an SS pin that is useful when they act as a
> slave controlled by an external master. Since this library supports
> only master mode, this pin should be set always as OUTPUT otherwise
> the SPI interface could be put automatically into slave mode by
> hardware, rendering the library inoperative. It is, however, possible
> to use any pin as the Slave Select (SS) for the devices. For example,
> the Arduino Ethernet shield uses pin 4 to control the SPI connection
> to the on-board SD card, and pin 10 to control the connection to the
> Ethernet controller.

The Example code given for the teensy board on the other page you linked has:

    pinMode (slaveSelectPin, OUTPUT);

in its setup() function.

So that's what you're missing.
Setting the pin high or low is not going to achieve anything if its not an output.

Remember that SPI can access many diffrent devices using the same MOSI/MISO/SCK pins, but each slave device has its own Slave-Select pin which needs to be individually driven by the master.
Your master can therefore have many different SS pins, all set as outputs - and there is no single standard pin for this.


message:
Moving motion sensor?

Long story short, I'm trying to build some form of device that you can wear and it will detect when something moves behind you. I wanted to use PIR sensors for the motion detection, but I have no idea if they can detect objects if you're moving. Any ideas?

body:
PIR sensors detect the movement of a warm body *relative* to the location of the PIR sensor.  Therefore if the PIR sensor moves then the location of a static object *relative to* that PIR sensor will change and motion will be detected.

So no, PIR is not really suitable for this.

TBH I can't, off the top of my head, think of a simple way of achieving what you want short of image processing with OpenCV on something considerably more powerful than an Arduino.


body:
OP didn't really specify the actual requirements other than detecting movement and wanting to use PIR while in motion.

PIR (Passive Infrared) implies looking for warm bodies.  In general, PIR motion sensors look for the presence of thermal radiation that moves between the individual parts of the sensor.  On TV it is shown that you can fool PIR detectors by carrying a large cold panel between you and the detector. ;-)

They also detect reflected thermal radiation that is moving.   It does not need to be a direct view.  So moving the sensor around outside would pick up a lot of reflected IR sunlight changes.  And certainly incandescent lights would do the same since about 80% of their emitted energy is IR.

The way they are designed, (with lenses like a bee's eye) they are more likely to detect your own arms swinging back as you walk and generate false alarms that way.  So you would need some kind of mounting arrangement that only allowed it to "see" directly behind.  And even then only in a dark room.

PIR sounds like a lot of trouble for an application like this.  (As in, probably not suitable)

Here is a decent instructable that explains how they work:  http://www.instructables.com/id/PIR-Motion-Sensor-Tutorial/

If PIR is not a be-all requirement, here is an alternative to be considered, even though it would require some work to get it right:
Radar
-----

Here is a nice, inexpensive radar unit that will arrive eventually on the slow boat, and the price is right.  It could work well in motion if you program it to detect changes that occur at speeds faster than your own motion.  And you would want to program a pulse gate it so it only senses objects at more than a certain distance behind you.

Anyway, in the spirit of hacking, I offer this idea:

LFS-DC04 2.7GHz Microwave Radar Module DC 5V
-----
  http://www.ebay.com/itm/262662221979

It is small enough to wear.  But it is slow, so I wouldn't recommend using it to detect intruders with violent intent.  I believe it would be good mounted on a bicycle-pulled trailer or something like that, to make sure you know if something is coming up on you too fast.

Product Introduction:
-----
    1.Model:LFS-DC04
    2.Frequency:2.7GHz
    3.Size:40*22mm
    4.Input Voltage:DC 5V
    5.Output Type:level signal output
    6.Connection Method:VCC,GND connect with positive negative input, OUT,GND signal connect with output
    7.Installation Height:1-3.5m
    8.Sensing Ditance:5-8m
    9.Delay Time:30s(quick testing mode is 4s)
    10.Sensing Angle:360 degree

It is low enough power that it shouldn't fry your kidneys.  Probably very similar to sitting next to a high-power WiFi router all the time, or like having a cellphone in your pocket with WiFi and 4G turned on all the time.


body:
A PIR is entirely passive. The sensor has an enclosed vertical and horizontal IR receptor which reacts to the change of IR coming through a faceted lens, to accentuate the effects of movement, striking the surfaces through a small window on top.
Having a passive system attached to a moving body would result in mostly false positives.
It could be worth looking at active systems such as video, microwave, or even ultrasound


message:
Getting the average of sound in last minute

I am reading sound input every 60 seconds and I would like to calculate the average of sound during that period using non-blocking code; what should I do to change the way that I calculate it in separated function as I need to do something else with other sensors.

    int calculateSoundValue(){
       int average = analogRead(0);
        // loop to calculate the average simple formula sum div nbr of calculated times
       return average;
    }

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

    }
    void loop() {
      // I donùt wanna calculate the average inside a loop but instead inside a function
      int value = calculateSoundValue();
      Serial.println(value);

      delay(600);
    }

**UPDATE**

Is this what you mean ?

    unsigned long previousMillis = 0;
    const long interval = 6000;
    int totalSamples = 0;
    int count = 0

        int calculateSoundValue(){
            int sound = analogRead(0);
            totalSamples+= sound;
        count += 1;
           return totalSamples/count;
        }

    void setup() {
      // set the digital pin as output:
      pinMode(ledPin, OUTPUT);
    }

    void loop() {

      unsigned long currentMillis = millis();
    int totalSamples = 0;
    int count = 0
      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

      }
          int value = calculateSoundValue();
          Serial.println(value);
    }

body: The short answer is use millis() to keep track of time. You can also put all the time related stuff inside a class to have a nicely organized code. You can get more info about time management on the Arduino here. https://learn.adafruit.com/multi-tasking-the-arduino-part-1/ditch-the-delay


body:
You want to find the average of doing an `analogRead` over a minute, is that it?

How about this?

    unsigned long total;
    unsigned int count;

    unsigned long whenStarted;

    const unsigned long INTERVAL = 60000;  // one minute

    void setup ()
    {
      Serial.begin (115200);
      Serial.println (F("Starting ..."));
      whenStarted = millis ();
    }  // end of setup

    void loop ()
    {
      // one more sample
      total += analogRead (0);
      count++;

      if (millis () - whenStarted >= INTERVAL) // is a minute up?
        {
        Serial.print (F("Average = "));
        Serial.println (total / count);
        total = 0;
        count = 0;
        whenStarted = millis ();
        }
    }  // end of loop


body:
I assume what you actually want is to measure sound intensity. This is
significantly more involved than just averaging the samples you read. I
have written a few weeks ago a program that does exactly that: it
measures the sound intensity and sends those measurements through the
serial port. It is a pretty short program (43 lines of code) you may be
able to adapt to your needs, so I am now sharing it as a GitHub gist:
[sound-meter.ino](https://gist.github.com/edgar-bonet/e693799f58a545ca89a2).

In order for this not to be a link-only answer, I'll try to explain the
program's inner working, and go through the theory of measuring sound
intensity on an Arduino. But first let me put here a disclaimer: a
“real” sound level meter should have a frequency response that complies
with some standards, and it should be calibrated to absolute levels.
This program only provides uncalibrated readings with whatever frequency
response its analog hardware has.

## Signal conditioning

Four measuring sound on an Arduino, you obviously need a microphone,
but you also need some kind of interface circuit between the microphone
and the Arduino. The purpose of the interface is to “condition the
signal”, i.e. to make sure the Arduino gets a voltage in the proper
range for it's analog-to-digital converter (ADC). It's typically an
op-amp based circuit that provides some amplification and also adds a DC
bias to avoid clipping the negative side of each oscillation. Ideally,
the DC bias should be around Vcc/2, i.e. 2.5 V on an Arduino Uno.

See this [SparkFun microphone
breakout](https://www.sparkfun.com/products/9964) for an example on how
such a circuit may be built (click on “Schematic”).

## ADC sampling

Once you have a properly conditioned analog signal, you have to sample
it fast enough to catch all its spectral content. The [Nyquist–Shannon
sampling
theorem](https://en.wikipedia.org/wiki/Nyquist–Shannon_sampling_theorem)
tells us the sampling rate should be at least twice the highest
frequency in the signal. For audio signals, sampling rates of the order
of 8 kS/s (kilosamples per second) are typical of low quality,
telephone-like applications, whereas high quality audio would run at
44.1 to 48 kS/s.

The ADC of the Arduino Uno, in its default configuration, takes
104 µs to convert one sample. If you just call `analogRead()` in a
tight loop, this gives a sampling rate of about 9.6 kS/s, which is
fine for this kind of application, unless we have to measure noise above
4.8 kHz. The problem with this approach is that `analogRead()` is a
_blocking_ function. Calling it in a tight loop means the program will
spend most of its time just waiting for the ADC. If you do anything else
in the loop, not only will the sampling rate be lowered, it will also
become unsteady, which is generally not desirable.

In order to avoid blocking the CPU, we have to forgo `analogRead()`, and
instead get our hands dirty with low-level configuration of the ADC. The
ADC of the Arduino Uno offers a so-called “free running mode”, which is
well suited for this kind of application. In this mode, the ADC starts a
new conversion as soon as the previous one is done, ensuring a very
consistent sampling rate of 9.6 kS/s. It can also trigger an
interrupt after each conversion, in order for the interrupt service
routine to retrieve and process the sample. See the [datasheet of the
ATmega328P](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf)
for details on configuring the ADC.

## Removal of the DC bias

Once we have the digitized samples, the first thing to do is to remove
the DC bias that was added by the interface circuit. If the bias is
stable and known (maybe determined by experiment), this only involves
subtracting a constant. If it is not known, it can be estimated by
running the samples through a digital low-pass filter with a cutoff
frequency below the range of interest. Subtracting the output of a
low-pass filter is essentially building a high-pass filter. As an
alternative, a numerical derivative (difference between consecutive
samples) can be used as a crude high-pass filter. This, however, will
bias the sensitivity of the detection towards the high end of the
spectrum. Depending on the noise you want to detect, and on the
background noise, this could be acceptable for your application.

In the program I am sharing, I assume the DC bias is known: it's the
`dc_offset` constant at the beginning of the program.

## Instantaneous intensity

With the DC bias removed, the signal we have is a digital image of the
sound picked by the microphone. It could be tempting to just average it
as is. This, however, would just give zero, as the positive fluctuations
of the signal would cancel the negative ones.

The are several options to solve this problem. We could do a peak
detection instead of an average, or we could take the absolute value
before averaging. The most popular option is probably to compute the
squares of the samples. Since the square of a real number is always
positive, this avoids the averaging-out problem. But the square has also
a deeper physical meaning: it is proportional to the [sound
intensity](https://en.wikipedia.org/wiki/Sound_intensity), i.e. the
energy carried by the sound wave.

## Low-pass filter

The intensity computed above is a very fast varying quantity. If the
signal is a simple tone of constant frequency and volume, the
instantaneous intensity fluctuates between zero and some maximum at
twice the tone frequency. In order to recover the “constant volume”
property of the sound, we need to perform some sort of averaging or, in
other words, we need a low-pass filter.

There are many ways to implement a digital low-pass filter. The most
intuitive may be to group the samples into batches, and then compute the
average of each batch. However, this is neither the best nor the most
efficient to implement. When I need a quick and simple low pass filter,
I generally use an [exponential moving
average](https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average).
This is the discrete-time equivalent of an analog RC filter, and it can
be implemented very efficiently by remembering the previous output and
updating it as

    output += input - output / N;

where, for efficiency reasons, N should be a power of two. The filter's
time constant is N/fs, where fs is the sampling
frequency. In the program I use N = 256, which makes the
division virtually free. This gives a time constant of 26.6 ms. You
can tune the time constant to your needs simply by changing N, but make
sure it is still a power of two.

## Decimation

If you only want to trigger an event when the sound intensity exceeds a
defined level, you may not need this. But if you have other processing
to do with those measurements, it is probably not useful to process more
than one intensity reading per time constant of the previous filter.
That's why the program has a decimation step. This is simply the ISR
periodically signaling the main program that an intensity reading is
available. Notice that, since the sample count is an 8-bit variable, it
automatically counts modulo 256. If you want to increase the decimation
factor, you should make `sample_count` wider and mask out the bits you
do not need.


message:
Clone vs Counterfeit (Arduino)

On [this][1] page on Arduino's website, it states

> "HUNDREDS OF COMPANIES AROUND THE WORLD ARE USING IT *[Arduino Software]* TO PROGRAM THEIR
> DEVICES, INCLUDING COMPATIBLES, **CLONES, AND EVEN COUNTERFEIT**."
(Emphasis Added)

With open source electronics, what is the difference between a clone, and a counterfeit?

  [1]: https://www.arduino.cc/en/Main/Donate

body:
This is not gospel, but here is what those terms are generally used to indicate (as I understand it):

- compatible: a dev board which is compatible with the Arduino IDE/toolchain. The Arduino UNO uses an ATmega328 MCU, while other platforms may use different MCUs i.e. there are multiple MCUs that are compatible with the Arduino IDE. It may or may not have the same form factor. Keep in mind that this term can also be used for shields, "Arduino-compatible" shields are add-on boards that are meant to mate with an Arduino. The [Sparkfun RedBoard](https://www.sparkfun.com/products/12757) is an example.

- clone: a dev board which has the same (or very similar) circuitry as an Arduino and the same physical board/layout. They are branded differently, but are, for all intents and purposes, exactly the same as a real Arduino. These boards are permitted under the open-source licensing of the Arduino design. An [Freeduino](http://www.freeduino.org/freeduino_open_designs.html) might be an example.

- counterfeit: a dev board which is identical to an original Arduino, and is branded and sold as an original Arduino. As I understand it, the open-source licensing _does not_ permit this, however, this does not deter the flood of shops churning out counterfeit Arduinos. A search on eBay or Aliexpress will turn up loads of examples; note the [Arduino guide to spotting counterfeits](https://www.arduino.cc/en/Products/Counterfeit), in general, the silkscreen is blue and the quality of assembly is not quite as good.

The difference between "compatible" and "clone" is a bit blurry, but it's not really important. The main difference between counterfeit and non-counterfeit is that counterfeit Arduinos are boards that are _not sold by Arduino but are branded as such_.