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

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

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.

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


text:
Adding Attiny to Arduino IDE - attiny\variants\platform.txt file missing
I followed this guide 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. How do I make it work?

Open the "Preferences" dialog in the Arduino IDE.
Click on the symbol next to "Additional Board Manager URLs"

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

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.

Click OK to close the Preferences dialog box.
In the Tools menu / Board select the Boards Manager:

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

Once done, close the Board Manager dialog box.
You should now be able to select Attiny from the Boards menu:

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

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.

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.

I tried to find up to date tutorials and what I found is linked in my question. I think this answer would better qualify as a comment since it's like link-only, but without the link...

The tutorial was using version 1.0, while you are using 1.6.8. That is why you are getting the error. So that is an answer. PS The tutorial is more than 4 years old, and the github repo is from 2011.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


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

I'd look into the Device Manager.

This has nothing to do with electronics design. You are best off searching on something like SuperUser or Arduino.SE to find out how to locate serial ports in windows and the Arduino IDE respectively.

@TomCarpenter I didn't know Arduino.SE has been resurrected again (how many times was it already...?). And many of those who said Arduino.SE should not be created argumented that all Arduino quesrions can be answered on Electronics.SE.

Looks like EE.SE doesn't agree with you. :) The IDE should detect which port the Arduino is on. I never have to brute-force search for mine. I just bought arduino - which Arduino? You may have to install a device driver. There is a "drivers" directory with some in it.

@NickGammon Do not misunderstand. I am supporting Arduino.SE! I just didn't know it's resurrected - I had all my questions from previous betas migrated. Although I see that I already have some question here. Maybe I forgot. And after installing drivers, the arduino now appears next to the correct port, though I still have to manually select it.

Glad that helped. I turned my comment into an answer to make it more permanent. I have found on Windows / Ubuntu and Mac that if you unplug and replug the Arduino, it often gets assigned a different (COM) port and you may need to select it from the Tools -> Port menu.

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.

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

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

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


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

Possible duplicate of Adding Attiny to Arduino IDE - attiny\variants\platform.txt file missing

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

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

I was asking how to do it on my local version. Imagine I wanted to add another chip when I have no internet connection...

If you do not have internet how are you going to get the toolchains?

If you have the toolchains; mod the boards.txt

So, here I am, several months after asking this question. Funny how useless answer has remained useless. Seriously, why should I have to wait for someone to accept my pull request? And this answer also doesn't cover how to actually add the signature in the file. You could really answer any question by telling the OP to do it himself.


text:
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();
}

Have you tried printing analogValue in your loop to verify that it is behaving the way you expect?

It seems to me that you are coding to always display something on the LEDs:
  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();
      }
    }

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


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

If I understand your question, you could use a relay to switch the 1.5V supply.

That's what I'm thinking, but a 12V relay seems like alot. I know it doesn't have to be the same voltage as what it's controlling, but I was wondering if there was something more light-weight.

Mainly because I don't want to power it with a car battery and I don't know anything about converting from AC to DC. I guess I could buy a 12V AC->DC adapter...

Not all relays are 12V...

I used to wake up by the relay clicking on inside my stereo, even before the music started. So if you are a light sleeper (which it sounds like), you might not want to use a relay.

I realized I actually have an old variable 1.5V-12V AC->DC wall-wart that I can probably use.

I suggest a simple setup (similar to my temperature and humidity sensor 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.

Thanks, that's a great writeup. I'm a beginner with this stuff, so I think that is probably a little more advanced than I'm looking for. It looks like I could just buy the 12V timer relay for less money and plug it in with my wall wart. My only concern is if it would waste too much power.

A timer relay won't use much power.


text:
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?

Copy the EEPROM variable into RAM (ie. into a character array). Then use strcat to append your word to the end of it. Allow enough room for the finished words, and the terminating 0x00 byte.

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.

The preprocessor solution is really nice - did not think of that :).

Thanks so much for the concise "big picture" overview. I loved learning about all of the methods. I think my first try will be with the preprocessor macro, since that shortens/simplifies the code (which was my main purpose), without changing the way the variables are written to or named. I would have to modify hundreds of lines of code if I changed the way the variables are stored, which I might experiment with if I have time/ambition in the future.

I just added the preprocessor solution to my code, and it worked beautifully without a hitch. It was really a very ideal solution to the problem. Thanks.

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

Thanks for the answer! This stuff is a little too complex for me, so I have some studying to do before it becomes more clear (same for @Nick Gammon's comment too, which I have to study more about). The AT24CXXX is on a DS3231 RTC board, and I think I had to look through some of the less common DS3231 libraries to find one that would work with the Due (it was easy to find ones that worked with the ATmegas). The code I used is located here: https://github.com/kriswiner/DS3231RTC. I think I still had to make some modifications to get it to work on the Due, but I don't remember exactly.


text:
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
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?

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

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?

Yes but how can i use it as a HID? I cant seem to be able to use the Arduino IDE as it cannot detect it so how would I be able to upload code to it as they did in the tutorial?

See amended reply.

authors: Παναγιώτης Βλαχάκης


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

"I'm pretty sure I connected the parts correctly" - You may be pretty sure, but we aren't certain at all. Can we maybe see what you have wired up and how it is all connected?

Besides adding a schematic and a photo, you might explain how or why motor speed is related to "pressure" in your setup.  Ordinarily, speed is sensed using an encoder, or a tachometer, or a Hall sensor, or voltage readings, etc. rather than "pressure"

This won't make a difference but the ground and 5V from the arduino are not going to the correct spot on the breadboard. Change that to keep things standard, as if there were polarized parts there they would be dead. Also where does the red line go from the side of the flex pot?

I changed the polarity of the ground and the 5V, but it didn't seem to make a difference, as you stated.  I had the red wire going to negative in the picture, but now it's going to the positive.  The odd thing I noticed; I got tiny voltage readings when I pushed on the sensor, but much lower than they should have been, like 0.01-0.05, when it should've been more like 1 to 5 given how hard I was pushing.  So some voltage must be getting through, but somehow not enough.

How about uncommenting the logging code so you can see what it is reading with the motor shield installed and being commanded.  Also make sure that the motor shield doesn't wire something to A0, either as a control signal or as potential feedback (motor current sense, for example).

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)


text:
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

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

Can you post a schematic or a simple diagram of your circuit?

Is what a common problem? With no schematic, and no code, your question doesn't make any real sense. Please read How do I ask a good question?

@Nateowami, I have been updated my question with code and schematic. Do you have any experience with this? Because I think it should be something wrong with the Arduino.

@NickGammon I have been updated my question with code and schematic. Do you have any experience with this? Because I think it should be something wrong with the Arduino.

Have you checked your wires to make sure the wires for led2 and led3 don't touch? If they're touching that could make them sometimes light the wrong one. Also, check the wires for switch2 and switch3. What kind of switch are you using?

@Nateowami I checking the switch2 and switch3 with multimeter and it doesn't connected. I use lamp switch (on/off) not temporary switch. Simple question: It should be perfectly work, right? I also has different behavior, When I switch on, other lamp also on, less than 1 sec. Check my video https://www.youtube.com/watch?v=s6CxPuQya0g

Lose the delay(1000)

@Majenko what do you mean? I didnt understand. Sorry.

I mean delay is always a bad idea regardless of what you are doing - especially when you are reading switches and expecting them to respond in a normal fashion.

I would suggest reading this article https://hackaday.com/2015/12/10/embed-with-elliot-debounce-your-noisy-buttons-part-ii/ (and also part one). Elliot covers all about switches, switching noise and how to solve the problem (debouncing) in software.

Your question says you have “Pin 2 and 3 as INPUT_PULLUP” but in the code pins 2 and 3 are used as outputs to LED2 and LED3.  Please edit the question and remove the inconsistency. Also remove “interrupt” from the question title because it appears the question has nothing to do with   interrupts.

Why when I press switch at PIN 2. SOMETIMES PIN 3 also getting input. - you have LEDs on Pin 2 and Pin 3, not switches. Thus your question doesn't make any sense. Please edit the code, and the schematic, so at least there is some internal consistency.

@NickGammon I changed my post already.

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


text:
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
/*
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;
}

PCMSK0 &= 0b00000000; //Clear all bits - wouldn't PCMSK0 = 0; be a lot clearer? Meanwhile I agree with Gerben's answer. Try "guarding" your access to multi-byte variables set by interrupts. See Interrupts.

You have a scope, you used it to look at the motor pulses. Did you look at the encoder pulses also? How do they look like? 2) On a quadrature encoder, I would expect at most one channel to be “bouncy” at any given time. Then, if you use the encoder in the usual way, you should get a sequence of +1, −1, +1, −1... adding up to zero. 3) The standard idiom for setting the AVR I/O registers is PCMSK0 = _BV(PCINT3) | _BV(PCINT4);, which looks clearer than PCMSK0 &= 0b00000000; PCMSK0 |= 0b00011000;, at least to those familiar with AVR programming.

Do you have a proper shared ground between quadrature encoder outputs and the Arduino? If so, then @EdgarBonet is right. Quadrature encoders can bounce like crazy, so you really do need to read the encoder properly, determining the step direction and all from each and every read. This way, if it bounces +1 and then -1, or any other sequence, 100 times in a row, you end up knowing what the new location is, and thereby you've debounced it too. Try adding a 2.2uF cap on each quadrature output too, to help a little bit with hardware debouncing.

Properly reading the encoder is the software debouncing you really need.

Is your rotary encoder electrical or optical?  I ask as I wonder if you have issues with switch bounce or possibly the optical receiver swithing on and off at a boundary. If this is the case, one way that may help solve it is to properly decode the quad encoded pulses.  This blog post shows a reliable way of decoding quad encoded pulses: https://thewanderingengineer.com/2014/08/11/rotary-encoder-on-the-attiny85-part-2/  Regads,

An alternative to doing the debounce in the processor is to use an chip designed for the purpose.  Here's one that may be suitable:  https://www.elmelectronics.com/ic/elm402/  Regards,

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.

Hi, and thanks Gerben and Nick. I made the changes you recommended but they actually seemed to make things worse, not better, in that even without the step motor running I was getting multiple triggering on each of  the RE channels.

Oops - wanted a new line and pressed return but that sent the comment before I had finished. So, excuse the lack of formatting from now on. I have now reached the conclusion that I need to debounce the Rotary Encoder. I had ASSUMED that as it's an optical encoder it wouldn't require debouncing but I now think my assumption was wrong. I am going to make a small hardware debouncer using RC timing and a 74HC14 hex inverting Schmitt trigger IC. Hopefully hat will solve the problem. The good news is that the actual step motor pulses are  counted without any problems. Thanks, Hugh.

There's no real bounce here, but probably not as clear a transition as you'd expect. My guess is a schmitt trigger alone will work. Even though my answer doesn't solve your problem, it still point to a problem you might account with your code.

Hi, I tried to use my scope to look at the encoder outputs but I don't know how to use it properly and couldn't get meaningful results. I have made the debouncer board, using ca 5 mS delay on each encoder channel and, finally, it all works as it is supposed to. I first had this problem in early December so it has taken all this time to get it solved. Actually bought my scope to help with this specific problem. Thanks again to everyone who answered and commented. Regards Hugh

@HughGilhespie, if the problem is solved now, please post an answer to your own question and mark it as solved.


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

I don't see a "pinMode" statement anywhere in your code. Where do you set SS as an output?

@brhans I was following the given table: https://www.arduino.cc/en/Reference/SPI

@brhans https://www.arduino.cc/en/Reference/SPIBegin States that SS is set to high, which is Pin 10

@brhans In addition, this link states "Arduino automatically defines SS as the pin numbers for the selected board". https://www.pjrc.com/teensy/td_libs_SPI.html

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.

It doesn't seem to be this, I have updated the code and I have the same issue, where the SAMD11 doesn't have a lit LED, meaning it is waiting to receive something.


text:
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?

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.

New information:  I hooked up a PIR sensor and tried moving with it hanging over my shoulder.  It would not stop triggering constantly.  I couldn't hold still enough to make it stop.  So I believe that isn't going to work for you.

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.

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


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

Do you know how average is calculated?

Do you know what sound is?

sleep(600) doesn't look like a minute, did you mean delay()? To do stuff with other sensors, you would have to have non-blocking code when you do the averaging on the reading.

@RSM Yes! that's the point behind my question; how can I make it non-blocking at the same time, I am doing a delay

@Avamander Harsh Answer!; Any way; in case you are familiar with arduino, you know that I meant how to make calculate the average on non-blocking way.

@user3378649 you didn't make it very clear that you wanted to make use of non-blocking code, so to a point it wasn't harsh, just practical and straight forward.

@user3378649 to make non-blocking code you can use the mill is() function, most suggest a look at the blink without delay example. Delay will block your code, I know timer interrupts still happen when a delay is running, so timer interrupts are what you can look into. Also 60*1000mS = 1 minute.

You don't need fancy software to tell you what the average sound over a minute will be... The answer is zero - or as near as makes no odds.

@RSM Please can you check the UPDATE, I tried to implement what you suggested; double check and enlighten us with your suggestions.

@Majenko I am trying to see whether there was a movement in the last minute or no; by using sound sensor

@RSM Then the average is not what you want - what you want to do is listen continuously and decide from moment to moment if there is sound above your trigger threshold or not and remember that fact - then once a minute look at what you have remembered and act on it.

@Majenko I don't audio stuff, but I agree with you on average being a waste of time, I was only thinking of the implementation methods. The OP might as well use a peak detector.

@RSM That may have been misdirected ;) It was supposed to be directed to the OP...

@Majenko its chilled :), any way it made me think further than the obvious, and the OP will have a pretty busy inbox now :)

@RSM It's the classic X-Y Problem - the OP thinks they know what they want and how to achieve it, but can't work out how to implement that method - however the underlying method, and their basic understanding of it all, is completely wrong, so even if they manage to implement it as they think it should be it still isn't going to work. They're basically asking the wrong question.

@user3378649: Looks like you do not know what sound is... It's not the average of the signal you analogRead(), it's the fluctuations of that signal above and below its average. The closest thing to “average of sound” you can get is the RMS of the AC part of the signal. You can compute that as low_pass(square(high_pass(signal))).

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

Thanks! can I put  total += analogRead (0); count++; on q function and replace it like I did

...but as already pointed out, averaging the readings won't accomplish anything useful

Thanks! can I put total += analogRead (0); count++; on q function and replace it like I did - I don't know what you mean by that.

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

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

You probably mean micros(), not millis(): If you want to sample the ADC at rates relevant to audio signals, millis() will not provide fine enough resolution.


text:
Clone vs Counterfeit (Arduino)
On this 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?

i think when it is COUNTERFEIT, it also uses the same name. like an imitation brand. but CLONE just copies the circuitry under another name.

Why would you migrate this Nick... The distinction between clone and counterfeit is not specifically about the Arduino, the same thing could have been asked about the Raspberry Pi, the RepRap or SparkFun products, for example.

I agree that my question should have been kept in electronics.  It can apply to any device.  If anything move it to open source as that is broad but related.

The question is based on Arduino and fits in Arduino.SE (Nobody would've migrated it towards EE.SE from Arduino.SE). And, EE.SE seems to have an aversion from any question where the word: "Arduino" is used. Which might be a good thing. Since it gives Arduino.SE a reason to live. But it does indeed feel a little odd or "agressive" to some extent.

This a reference to the terminology defined in Massimo's https://blog.arduino.cc/2013/07/10/send-in-the-clones/ essay, right?

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

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

Counterfeit: the vendor says/implies that the Arduino board is produced by Arduino/Genuino, an "original", but it is not. The screen-print is the same, but looking closer at the components and PCB there are some differences. You think you can turn to Arduino/Genuino for product support but you cannot.
Clone: the vendor states that the board is a "compatible copy", uses all the open-source bill-of-material, schematics, etc, (or slightly changed for cheaper components) when produced, and it is obviously not produced by Arduino/Genuino. You know that you cannot turn to Arduino/Genuino for product support.
The punishment for selling and buying (!!) counterfeit fashion in Italy is very severe.
Counterfeiting is a trademark violation issue.
Cheers!

I'm not sure how the buying counterfeit fashion in Italy is related, but that's an interesting point. It might be usefull to note that originals or clones of known brands are often of a higher quality. But that counterfeit might be useable for hobby projects (but often not in a final product).

@Paul the fact counterfeits might be usable in an hobby project doesn't change the fact using, buying or selling counterfeits breaks the law. For hobby projects you should use cheap clones: never use counterfeits, just by buying them you are supporting thieves.

@Roberto it's completely legal to copy the Arduino hardware. But not to copy the brand(name) I believe.

@Paul that's correct and it's exactly what distinguishes a clone from a counterfeit. What I'm saying it's ok to buy cheap clones (which is something I often do), but I strongly advice against counterfeits, no matter if it's for hobby projects or not.


text:
Multi-file arduino esp8266 sketch sharing a reference to server
Transferred from stackoverflow on the advice of @Gee_Bee:

I can get Writing a Library for Arduino to work as well as
  Breaking a sketch into multiple files and Classes within Classes
  - Initialiser Lists. I can even get extern references to variables to work but referencing the an instance of ESP8266WebServer in
  different files is still beyond me.

As my sketches get bigger, the code looks awful as one file and the number of global variables is too high.
For the webconfig part of my sketch the device attempts to get online and if it fails it scans for available Wi-Fi networks, goes into Access Point Mode, starts a server, sends the list of SSID's and listens for a response of an SSID/password pair. The server is only for the configuration.
Ideally I'd like the cleaned up main.ino file to look like
    #include "config.h"
    void setup(){
        Serial.begin(115200);
        Serial.println();
        Serial.println("--------------------------");
      Serial.println("ESP8266 multifile");
      Serial.println("--------------------------");
      getOnline();
    }
    void loop(){
        if(IN_CONFIG_MODE){
           server.handleClient();
        }
    }

with a config.h something like..
    #ifndef config_h
    #define config_h
        #include <ESP8266WiFi.h>
        #include <ESP8266WebServer.h>
        ESP8266WebServer server;
        void getOnline();
    #endif

and then a config.cpp where it does all stuff described above yet gives the main.ino program access to the server instance so it can listen in the main loop.
#include "config.h"
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

char *espssid = "espAPsb";
char *ssid = "street_no_vale2";
char *pwd = "jjjjjjjjx";
char ssids[300];

extern server(80);

void handleRoot(){
    server.send(200, "text/html", "
root of espAPsb AP server
");
    //send json of available ssids
}

void scan(){
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");
}

void setupAP(){
    WiFi.softAP(espssid);
    server.on("/", handleRoot);
    server.begin();
  Serial.println();
  Serial.print("connected as AP ");
  Serial.println(espssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.softAPIP());
}

void getOnline(){
    WiFi.begin(ssid, pwd);
  int tries =0;
  int success=1;
  while (WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
    tries++;
    if (tries==15){
      success=0;
      Serial.println("WiFi not connected");
      scan();
      setupAP();
      break;
    }
  }
  if (success){
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  }
}


text:
When I call the tone function on a Uno, why do I not have to declare the pinmode in setup?
When I call the tone function on a Uno, why do I not have to declare the pinmode in setup? Like so:
// Simplest tone
void setup() {
}

void loop() {
    tone (8,500); //on pin 8 output 500 Hz
}

Because the tone(hertz) code initializes the pinmode, along with the timer/counter control registers to produce the appropriate frequency.
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)
{
  uint8_t prescalarbits = 0b001;
  long toggle_count = 0;
  uint32_t ocr = 0;
  int8_t _timer;

  _timer = toneBegin(_pin);

  if (_timer >= 0)
  {
    // Set the pinMode as OUTPUT
    pinMode(_pin, OUTPUT);
   ...

See Tone.cpp - line 255 for the source.


text:
Arduino development vs nRF51 development
Originally I had an idea to develop an Arduino-compatible project using an ATmega328P, some sensors and the nRF51822 as the BLE radio. As I progressed, I realized that if I relaxed the Arduino-compatible requirement, I could actually do away with the ATmega328P and write the application directly on the nRF51822 as it is a more capable MCU (32-bit, more memory, faster, has SPI, I2C and TTL serial, etc.) I'm not familiar with writing native applications for the nRF51822 but it seems much more complicated.
For someone that has experience in both platforms, can you please list some of the tradeoffs of developing using an ATmega328P for application + nRF51822 for radio and using the nRF51822 for both application and radio?

This sometimes even bothers me. That moment you realize that the "slave ethernet module" is running Linux on an 88Mhz x86 CPU with 256kb sram. And that you realize that your tiny MCU is the master (and 10x cheaper).

First, there are various ports of the Arduino environment to the NRF51822, but I'll leave that aside for the moment and address using Nordic's codebase or the mbed one.
Generally speaking, one of these paths will put you more in the current "real world" of professional level embedded development, in which the ARM cortex parts play a leading role.  You will have conventional multiple source file projects tied together by more ordinary means such as a Makefile or explicit IDE configuration, rather than the rather oddball way the Arduino IDE has evolved to do things.  The basic lower level APIs you will be writing against will be much more conventional - ie, your code will start in main() rather than setup() and loop(), you will generate debug messages with printf() or similarly styled member function on mbed, rather than Arduino type print()/println() (though of course you can use printf() on an Arduino with some setup).  This tends to make it a lot easier to port or share code between this and other embedded systems, or even between an embedded system and a phone or desktop communicating with or simulating it.  Of course you can treat an Arduino as a plain ATmega and do this with that as well, up to the limits of the CPU and its memories.
People tend to think of the mbed option as being an online "toy" for certain boards, but you can generally use others just by setting it for a board using the same MCU in a similar way.  And in most cases you can download a zipfile of a project with a Makefile in it that will drive arm-gcc or a few other compiler choices.  The NRF51822 does come in varieties with different onboard storage sizes, and this can sometimes require care and attention to the linker script - in a few cases a project that fits in the online build (apparently with the Keil compilation engine as its backed) will not build in the downloaded GCC configuration unless you adjust the linker script to reduce the stack size, or perhaps change compiler optimization levels.
Countering reasons you might end up keeping the ATmega would be if you need some of its I/O peripherals or its 5v I/O capability.  For example, the NRF51822 has limited hardware PWM capability compared to an ATmega so that must generally be done in software.
If you are really at home with "The Arduino Way" switching to anything more traditional may take some adjustment of thinking and habits.  On the other had, if you look at the benefits of Arduino being the variety of works-out-of-the-box, easily modified examples you can use to explore the possibility of a project, but often find yourself annoyed by the legacy of its countless quirks and atypical approaches in the longer run, then you'll probably find the adaptation to using the NRF51822 directly to have been worthwhile.

Thank you. In my application I'd like to attach at least a GPS, an IMU, a microSD adapter and perhaps temperature/barometric sensors. These take up all the UART, I2C and SPI interfaces. No need for PWM. Would this be a reasonable way to go to remove the need for an extra IC at the cost of more complicated development?

That seems like it should work, yes.  Much of your challenge will be in figuring out organized code to service the peripherals, and in how this integrates with the BLE or whatever other use you are making of the radio.


text:
Multiple Wireless Sensors to an Arduino
I am looking for ideas on how to connect 12 sensors to an Arduino wirelessly.  The sensors will be about 10ft from the Arduino.  They need to send one byte of data every 100ms-250ms to the Arduino in an organized manner.

I have investigated MQTT and pubsubclient, but have not found a way to make an Arduino a Broker, and have been told it is very inefficient for my application.
I have looked at NRF24L01, but it appears to be limited to just 6 pipes to receive data in an organized fashion.
I researched Xbee, but have been told that it cannot keep up with the data rate.

Other suggestions are appreciated...  Thank you.

You can do it with an NRF24L01 using just a single pipe.  Simplest would probably  be to actively query each node for data by including a node number in the query packet, but you can also have them identify themselves with a node number, transmit at slightly varied or random intervals, and perhaps put a reading number in each packet too so that they can transmit each reading more than once to generally accommodate any collisions on the occasions where the transmissions from two overlap.

Chris, would you happen to have any example Arduino code to do this, or a pointer to a reference, showing both the client and the server side?  This sounds like it may be the simplest solution...  I did not specifically mention in my original post that each sensor is wired directly to an arduino.    Thank you!

Did you got the things working? I am looking for - how to receive wireless data from four sensors with 512 Hz data rate(for each sensor and simultaneously) ? thank you.

Can any one help me in getting the Arduino code that how I can receive data from 6 sensors simultaneously on single master nrf24lo1...... Thanks in advance

I would recommend the nRF24L01.
You don't need one pipe per node - just one pipe.
Each pipe is effectively an address that a node responds to - having multiple pipes means you can have multiple addresses on one node (like aliases) - but of course you only need one address per node, and hence one pipe per node.
The range is more than adequate (with the antenna version I have managed to get hundreds of meters no problem) and the price is so low as to be negligible.

It might be easiest to send a UDP packet over WiFi.  There is no extra packet overhead for this "connectionless" protocol: no OPEN, no ACK/NAK, no CLOSE, etc.  The incremental cost for additional bytes is very small, so if you decide you need to send 2 bytes, or even 100 bytes, it won't affect the throughput very much.
If you can "batch" the bytes, that would be even better.  For example, could you send 8 bytes per node, once every 800ms-2000ms?  If not, WiFi speeds should allow the single-byte UDP packet to get through without much latency.  Do you know what latency the receiver can accommodate?  You might get lower average latency with batched packets, depending on the network access time (i.e., how long it takes to hop on to the air).
A roll-your own approach would be to use a raw RF transmitter/receiver with something like VirtualWire.  With proper synchronization from the "master", the slaves could each have their own time slot, avoiding collisions (which keeps the network access time low)

WIFI is going to add a lot of register-with-the-access-point type setup overheard before you can do that.  Probably the reason for considering it would not be any inherent advantages (its quite disadvantageous compared to the alternatives) but the ready, inexpensive availability of ESP8266 boards as sensor nodes on which the poster can run Arduino-style firmware.  It can also function as the sensor hub and if needed the AP - either in cooperation with the existing Arduino or potentially replacing it.

Use nRF24L01. To avoid collisions you can query the sensors (as Chris suggested in comment).
The setup would be:
Each sensor would have unique address. Central unit would transmit request and sensor node would respond to it. Central unit would have different address and all sensors would transmit to that address. You can also use data in ack to pack response.

Central node (Addr0) -> Sensor 1 (Addr1): Request
Sensor 1 (Addr1) -> Central node (Addr0): Response, sensor data
Central node (Addr0) -> Sensor 2 (Addr2): Request
Sensor 2 (Addr2) -> Central node (Addr0): Response, sensor data
Central node (Addr0) -> Sensor 3 (Addr3): Request
Sensor 3 (Addr3) -> Central node (Addr0): Response, sensor data
...

Thank you all again.  I am just becoming comfortable with programming the Arduino.  Would you have a link or example Arduino code to do this?   All the examples I have found just show a one-to-one communication.

Essentially all that is happening here is one-to-one communication, it's just that the hub has such an interchange with each node in turn.  One thing you will need to think about though is how long to wait for a reply, before moving on to try the next node.

Ahh...  understood.  What sort of delay/wait time would be typical?  Am I even going to be able to meet my data rate of 250ms?  That is, within 250ms I would need to obtain a reading from all 12 sensors...

There will be plenty of time, it's more a question of what is the best strategy for using it.

So how to connect the sensor? directly via I2C to the nRF24L01 transceiver, with another transceiver at the microcontroller end? Wouldn't you need a microcontroller at each end?