body:
Using Visual Studio for my Arduino project I am struggling to know the states of various pins during operation.

I do use the Visual Micro debugger but I don't want to have to set a watch for every pin.

How can this be done easily?

title: Is it possible to see a graphical view of digital and analog pin values?

Answers: 2

body:
The [Arduino Dashboard][1] project sounds promising but quite likely it loops through the I/O pins periodically and uploads the results to your PC. I'm guessing you want live monitoring (as opposed to snapshots) while your own program (not the Dashboard sketch) is running. In that case, you'd need to isolate the relevant parts of the Dashboard sketch and integrate them with your code, and unless your are looking for fairly low frequency signal changes, have a timer interrupt function that runs the Dashboard frequently, which will have an impact on your own code. If the signals are fairly low frequency you might get away with putting a call to Dashboard in your `loop()` function instead of running it from a timer interrupt. If you're looking for program bugs that are changing your outputs, once per `loop()` may be fairly useless. A timer-interrupt would be necessary, and might have to analyze the stack and output the names or addresses of functions that had run recently. At that point you'd be on your way to implementing a debuggerand may want to consider an in-circuit emulator or a bus analyzer to capture the event. Or get smarter about isolating the code responsible for the event until you have a manageable, printf-debuggable code segment.

  [1]: http://www.lvl1.org/2011/07/04/arduino-dashboard-app/

body:
Visual Micro provides this for you if you have the debug module enabled. It also optionally shows analog, memory and i2c. Read more about [Arduino debug and the digital pin viewer][1]

![enter image description here][2]

  [1]: http://www.visualmicro.com/page/Debugging-for-Arduino.aspx
  [2]: https://i.stack.imgur.com/TsFgI.png


body: I am trying to use the official arduino wifi shield, It works occasionally, but most of the time (when running the WiFi web server example code, or my derivitave program, it outputs `WiFi shield not present` on the terminal. I have tried updating the firmware several times, but it has not fixed the problem. Is the wifi shield always this unreliable? What can I do to fix it?

title: Arduino WiFi shield working intermittently, "WiFi Shield not present"

Answers: 1

body: Be sure the shield is not shorting out on the metal USB socket on the Arduino board. I don't know if this is still an issue but I've seen many Arduino boards with black electric tape on the top of the USB socket to insulate it from shorting out the shield.


body:
I just received a RC522 board and since i am new to RFID, I tried out some examples from ["Arduino RFID Library for MFRC522"][1]. Here's one of them
**rfid_default_keys**

    /*
     * ----------------------------------------------------------------------------
     * This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
     * for further details and other examples.
     *
     * NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
     *
     * Released into the public domain.
     * ----------------------------------------------------------------------------
     * Example sketch/program which will try the most used default keys listed in
     * https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys to dump the
     * block 0 of a MIFARE RFID card using a RFID-RC522 reader.
     *
     * Typical pin layout used:
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
     *
     */

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9           // Configurable, see typical pin layout above
    #define SS_PIN          10          // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

    // Number of known default keys (hard-coded)
    // NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
    #define NR_KNOWN_KEYS   8
    // Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
    byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
        {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
        {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
        {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
        {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
        {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
        {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
        {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
        {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
    };

    /*
     * Initialize.
     */
    void setup() {
        Serial.begin(9600);         // Initialize serial communications with the PC
        while (!Serial);            // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
        SPI.begin();                // Init SPI bus
        mfrc522.PCD_Init();         // Init MFRC522 card
        Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
    }

    /*
     * Helper routine to dump a byte array as hex values to Serial.
     */
    void dump_byte_array(byte *buffer, byte bufferSize) {
        for (byte i = 0; i < bufferSize; i++) {
            Serial.print(buffer[i] < 0x10 ? " 0" : " ");
            Serial.print(buffer[i], HEX);
        }
    }

    /*
     * Try using the PICC (the tag/card) with the given key to access block 0.
     * On success, it will show the key details, and dump the block data on Serial.
     *
     * @return true when the given key worked, false otherwise.
     */
    boolean try_key(MFRC522::MIFARE_Key *key)
    {
        boolean result = false;
        byte buffer[18];
        byte block = 0;
        byte status;

        // Serial.println(F("Authenticating using key A..."));
        status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
        if (status != MFRC522::STATUS_OK) {
            // Serial.print(F("PCD_Authenticate() failed: "));
            // Serial.println(mfrc522.GetStatusCodeName(status));
            return false;
        }

        // Read block
        byte byteCount = sizeof(buffer);
        status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
        if (status != MFRC522::STATUS_OK) {
            // Serial.print(F("MIFARE_Read() failed: "));
            // Serial.println(mfrc522.GetStatusCodeName(status));
        }
        else {
            // Successful read
            result = true;
            Serial.print(F("Success with key:"));
            dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
            Serial.println();
            // Dump block data
            Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
            dump_byte_array(buffer, 16);
            Serial.println();
        }
        Serial.println();

        mfrc522.PICC_HaltA();       // Halt PICC
        mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
        return result;
    }

    /*
     * Main loop.
     */
    void loop() {
        // Look for new cards
        if ( ! mfrc522.PICC_IsNewCardPresent())
            return;

        // Select one of the cards
        if ( ! mfrc522.PICC_ReadCardSerial())
            return;

        // Show some details of the PICC (that is: the tag/card)
        Serial.print(F("Card UID:"));
        dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
        Serial.println();
        Serial.print(F("PICC type: "));
        byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
        Serial.println(mfrc522.PICC_GetTypeName(piccType));

        // Try the known default keys
        MFRC522::MIFARE_Key key;
        for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
            // Copy the known key into the MIFARE_Key structure
            for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
                key.keyByte[i] = knownKeys[k][i];
            }
            // Try the key
            if (try_key(&key)) {
                // Found and reported on the key and block,
                // no need to try other keys for this PICC
                break;
            }
        }
    }

So i modified the code to see exactly what is happening there and here is my output:
![my output][2]

Everything looks fine, right ?
So i tried to modify it again by adding some more stuff to the *knownKeys* array
but it looks like that only the first key is used in the actual authentication.
Here's an output for the same card but i moved `{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},  // FF FF FF FF FF FF = factory default` to the end of that array.
![enter image description here][3]

So.. as you can see even if it used the right key, nothing happened.
For the solution i tried few things but without a success. Thanks in advance for answering.

  [1]: https://github.com/miguelbalboa/rfid "Arduino RFID Library for MFRC522"
  [2]: https://i.stack.imgur.com/LuWoT.png
  [3]: https://i.stack.imgur.com/FocJM.png

title: rfid_default_keys check with RC522

Answers: 3

body:
Call:

    if ( ! mfrc522.PICC_IsNewCardPresent()) return false;
    if ( ! mfrc522.PICC_ReadCardSerial()) return false;

before every re-authenticate.

---

According to NXPs application note ([AN1304][1]) regarding MIFARE CLASSIC cards (page 24/25):

> Each time an Authentication operation, a Read operation or a Write operation fails, the MIFARE Classic or MIFARE Plus remains silent and it does not respond anymore to any commands. In this situation in order to continue the NDEF Detection Procedure the MIFARE Classic or MIFARE Plus needs to be re-activated and selected.

1. `PICC_IsNewCardPresent` resets modulation parameters and performs RequestA - activates the PICC (Card).
2. `PICC_ReadCardSerial` basically just performs Select - with anti-collision algorithm.

In case there are multiple cards present it would be better to manually call `mfrc522.PICC_Select(&mfrc522.uid, mfrc522.uid.size * 8)`, the second argument tells it that you already know all of the bits for UID, thus it will select the same PICC that was selected previously.

  [1]: https://www.nxp.com/docs/en/application-note/AN1304.pdf

body:
If called:

<!-- language: lang-cpp -->

    if ( ! mfrc522.PICC_IsNewCardPresent()) return false;
    if ( ! mfrc522.PICC_ReadCardSerial()) return false;

before every re-authenticate.
You will skip the FIRST item in array `knownKeys`
so you will never test the default key `FF FF FF FF FF FF`.

body:
Based on some experimenting, I believe the 1st key is skipped for one of two reasons:

 1. If you follow the code flow, in `loop()`, `PICC_IsNewCardPresent()` and `PICC_ReadCardSerial()` called. If a "new" card/tag is present, then `try_key()` is called which calls `PICC_IsNewCardPresent()` [and `PICC_ReadCardSerial()`] again. Since the card/tag is not "new", `PICC_IsNewCardPresent()` returns false.
       or
 2. It appears that if the correct key is the default of all 0xFF's, then a call to `PCD_Authenticate()` will fail.

I'm still working a new version of rfid_default_keys to fix the problem.


body:
I bought ESC from [**here**](http://www.rcbazaar.com/product.aspx?productid=2443) but it rotates motor in one direction only.

 Is there any program which will control direction of rotation clockwise or anticlockwise with same wire configuration.

title: How to reverse BLDC motor using programming arduino?

Answers: 0


body:
I am looking as a first project after some simple project kits, to make a watering system for my indoor plants. I have seen  a few projects on instructables, so I went to look for components. I am not sure how to power the pump from the Arduino.

My idea is the following:

A bucket of water with a water pump inside. An irrigation system linked to the pump, which then goes to all the plants. The pump linked to arduino which turns it on and off based on a timer.

The components that I will be using are an Arduino uno and:

 - [DV12 subversive pump][1]
 -  [Irrigation watering kit][2]

Also I guess I will need some tube to connect the pump to the watering kit.

I am not sure how to connect and power the pump (12V) with the arduino. The arduino it self will be powered by a USB on a wall socket.

  [1]: http://www.ebay.co.uk/itm/351304928817
  [2]: http://www.ebay.co.uk/itm/271401027990

title: DIY Watering - Required components

Answers: 1

body:
I have some details about running motors etc. from Arduino pins at [Driving motors, lights, etc. from an Arduino output pin](http://www.gammon.com.au/motors).

Quite possibly what would work for you is a MOSFET - as Majenko suggested - connected up like this:

![Low-side MOSFET driver][1]

In this case you connect the positive side of your 12V supply for your pump to the pump, and the MOSFET sinks current to ground, when you require the pump on.

Don't forget the diode D1 which prevents damage from the inductive load of the pump generating high-voltage spikes.

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


body:
so here is the issue. I have a mega 1280, a handful of neopixels and a HC-SR04. I am using the New Ping library (tried both 1.5 and 1.6). I am trying to make a device that will tell my mom when she has pulled into the garage enough so she don't get hit by the garage door AND doesn't run into the wall. I wrote a bunch of code to handle the lights and what colors to do when and this part works perfectly. My issue is with the sensor. It works great except for 2 specific conditions.

1. if you are too close. I normally either cover one of the 2 sonic sensor part or just barley touch then with a piece of cardboard (or anything for that matter

2. If you go outside the scope of the max distance

when either of this are met, the ping sensor stops clicking and it just returns all 0's for the output. I am including the code less the part for the lights because even if i remove that part of the code, it still fails on those 2 conditions.

    #include <Adafruit_NeoPixel.h>
    #include <avr/power.h>
    #include <NewPing.h>
    #define TRIGGER_PIN  52
    #define ECHO_PIN     53
    #define MAX_DISTANCE 120
    #define PIN 6
    #define LEDNUM 8

    int codeFact = (MAX_DISTANCE / (LEDNUM * 3));
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDNUM, PIN, NEO_RGB +     NEO_KHZ800);
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

    void setup() {
      strip.begin();
        strip.show();
        for(uint16_t i=0; i<strip.numPixels(); i++)
        {
          strip.setPixelColor(i, strip.Color(0, 255, 0));
          strip.show();
          delay(50);
        }
        for(uint16_t i=0; i<strip.numPixels(); i++)
        {
          strip.setPixelColor(i, strip.Color(255, 255, 0));
          strip.show();
          delay(50);
        }
        for(uint16_t i=0; i<strip.numPixels(); i++)
        {
          strip.setPixelColor(i, strip.Color(255, 0, 0));
          strip.show();
          delay(50);
        }
        for(uint16_t i=0; i<strip.numPixels(); i++)
        {
          strip.setPixelColor(i, strip.Color(0, 0, 0));
          strip.show();
          delay(50);
        }

    Serial.begin(115200);
    }

    void loop()
    {
     delay(2000);
      int uS = sonar.ping();
      int dis = uS / US_ROUNDTRIP_CM;
      Serial.println(dis);
      /*
      Light code normally goes here
      */
    }

title: HC-SR04 quits pinging when distance < 0 || distance < MAXDISTANCE

Answers: 1

body:
The HC-SR04's range is 2cm to 300 cm, if you exceed this range or come below this range, which is exactly what you are doing, the utrasonic sensor will not receive any echo and hence there will be no data on the output.
If you bring it too close and since both the transmitter and receiver located close to each other, the receiver will not receive any ultrasonic.
Put a function that checks if the ultrasonic comes down to 2-3. If it becomes true beep a buzzer that tells you that you are too close. Don't let it reach 0.


body:
I have this HLK-RM04:

![enter image description here][1]

It came with  no catalogue or manual
all threads about it are in Chinese
after when I found the configuration webpage and changing it to client
it wont connect and it stopped board casting hlink wifi
how could i reset to factory settings?

After very long search I found an English manual.

![enter image description here][2]

What does Trst means ?
I don’t understand what I must do to reset it!

  [1]: https://i.stack.imgur.com/EvYip.jpg
  [2]: https://i.stack.imgur.com/Fwed8.png

title: HLK-RM04 wifi shield factory reset?

Answers: 1

body: Since no one has posted an answer, and I finally found one myself. Ground pin 10 for 6 seconds.


body:
At work, I have connected an Arduino to a security key (which has a 12v power supply) in order to give us a more versatile door lock.  Unfortunately, people keep removing the key pad, disconnecting the wires and re-connecting them (defective keypad I guess.)  In the process, I am afraid that they will accidentally send 12v into the Vcc, ground, digital in, and/or analog in pins.  What is the best way to protect my Arduino from the 12 volts?  I really need a component or two that I can to my pins.

Edit: it is difficult for me to describe this problem without mentioning the danger to all components.  Please describe ways to protect digital outputs [HERE][1]

  [1]: https://arduino.stackexchange.com/questions/13150/best-way-to-protect-a-digital-output

title: best way to protect a digital or analog input from 12volts

Answers: 1

body:
There are some suggestions at [Protecting Inputs in Digital Electronics ](http://www.digikey.com/en/articles/techzone/2012/apr/protecting-inputs-in-digital-electronics).

_Amended answer_

Testing of my earlier answer involving clamping diodes gave unsatisfactory results. Due to the small current flow the diodes allowed a considerable voltage to reach the input pin (like, 9 V).

The amended circuit below, tested with 12V input, satisfactorily keeps the Arduino input pin to 4.9 V, even with 12 V from the device. The current through R1 is around 7 mA which is what you would expect:

    I = V / R
    I = 7 / 1000
    I = 7 mA

The 1N4733A is a 5.1 V, 1 W zener diode which can therefore handle dropping 5 V at 7 mA.

In case you are wondering where the number 7 comes from in the calculations above:

* The input voltage is 12 volts
* The desired output is 5 volts
* Therefore we need to drop (12 - 5) volts over the resistor
* Thus 7 volts are dropped over the resistor

---

![Input pin protection][1]

Further reference material:

* [10 Ways to Destroy An Arduino](http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino)

* [Protection](http://www.thebox.myzen.co.uk/Tutorial/Protection.html)

* [Microcontroller Input Protection Techniques](http://www.kevinmfodor.com/home/My-Blog/microcontrollerinputprotectiontechniques)

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


body:
i want to implement a discrete transfer function at z domain with arduino UNO.I  know that i must do the inverse z transform and find the difference equation.Afterwards i must use PWM because arduino UNO has not DAC.
Is there anyone who knows about this ?and can help me.... i want a code as an example  .Thank you.

title: Implement a discrete controller /transfer function with arduino uno

Answers: 0


body: If i connect a switch to the reset pin, can I create an effective way of turning off the Arduino (overnight) without removing its power supply?

title: can I create an on/off switch for my Arduino using the reset pin?

Answers: 1

body:
Tests show that connecting Reset to Ground on a Uno reduces the power consumption from 47 mA to 41 mA. So it is hardly "off".

All that would do is stop the currently-loaded sketch running, and save a few milliamps.


body:
I'm attempting to fade a strip of ws2812 7 pixels in length. Below I am using a for loop to increment the color red. I can fade it to red (from blue) but it will do it one pixel at a time or it just stays blue, depending where I move my r for-loop to. I need it to fade from color to color all 7 LEDs at once.

I get no errors.

I don't understand the process of getting NUM_LEDS leds all into x then proceeding with my color changing. Seems like I'm grabbing one pixel, fading it to red, then another...

fastLeds 3.03 library, arduino 1.0.6

    #include <FastLED.h>
    #define DATA_PIN 6
    #define NUM_LEDS 7

    #define BRIGHTNESS 45
    #define COLOR_ORDER GRB
    #define g 50
    #define b 100
    int r;
    CRGB leds[NUM_LEDS];

    void setup(){
      FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);
    }

    void loop(){
      for(int x = 0; x < NUM_LEDS; x++){
        delay(10);
        leds[x] = CRGB(r,g,b);
      }
      FastLED.show();
      delay(10);

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

      for(int x = 0; x < NUM_LEDS; x++){
        for(int r = 0; r < 254; r++) {

if NUM_LEDS is holding the number 7 why can't I just do it like this below: leds[NUM_LEDS]?

          leds[x] = CRGB(r,g,b);
          FastLED.show();
          delay(100);
        }
      }
    }

title: Fading from color to color using for-loop FastLEDs

Answers: 2

body:
If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...

    #include <FastLED.h>
    #define DATA_PIN 6
    #define NUM_LEDS 7

    #define COLOR_ORDER GRB

    CRGB leds[NUM_LEDS];

    void setup(){
      FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

    }
    void loop(){

      // Let's take 256 steps to get from blue to red
      // (the most possible with an LED with 8 bit RGB values)

      for( int colorStep=0; colorStep<256; colorStep++ ) {

          int r = colorStep;  // Redness starts at zero and goes up to full
          int b = 255-colorStep;  // Blue starts at full and goes down to zero
          int g = 0;              // No green needed to go from blue to red

          // Now loop though each of the LEDs and set each one to the current color

          for(int x = 0; x < NUM_LEDS; x++){
              leds[x] = CRGB(r,g,b);
          }

          // Display the colors we just set on the actual LEDs
          FastLED.show();

          delay(10);
      }

    }

body:
Here is the initial 0-255 rainbow.  I dunno if this is what you are trying to achieve but i took initiative from @bigjosh's answer.  This just cycles thru each rgb from 0-255. @bigjosh does start red at 0-255 allowing for more for red colors.

    void loop(){

    //start from red
      for( int colorStep=0; colorStep <= 255; colorStep++ ) {

      int r = 255;
      int g = 0;
      int b = colorStep;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
          delay(10);
          FastLED.show();
          }

        //into blue
          for( int colorStep=255; colorStep >= 0; colorStep-- ) {

          int r = colorStep;
          int g = 0;
          int b = 255;

          // Now loop though each of the LEDs and set each one to the current color
          for(int x = 0; x < LED_COUNT; x++){
              leds[x] = CRGB(r,g,b);
          }

          // Display the colors we just set on the actual LEDs
      delay(10);
      FastLED.show();
      }

    //start from blue
      for( int colorStep=0; colorStep <= 255; colorStep++ ) {

          int r = 0;
          int g = colorStep;
          int b = 255;

          // Now loop though each of the LEDs and set each one to the current color
          for(int x = 0; x < LED_COUNT; x++){
              leds[x] = CRGB(r,g,b);
          }

          // Display the colors we just set on the actual LEDs
      delay(10);
      FastLED.show();
      }

    //into green
      for( int colorStep=255; colorStep >= 0; colorStep-- ) {

          int r = 0;
          int g = 255;
          int b = colorStep;

          // Now loop though each of the LEDs and set each one to the current color
          for(int x = 0; x < LED_COUNT; x++){
              leds[x] = CRGB(r,g,b);
          }

          // Display the colors we just set on the actual LEDs
      delay(wait_time);
      LEDS.show();
      }

    //start from green
      for( int colorStep=0; colorStep <= 255; colorStep++ ) {

          int r = colorStep;
          int g = 255;
          int b = 0;

          // Now loop though each of the LEDs and set each one to the current color
          for(int x = 0; x < LED_COUNT; x++){
              leds[x] = CRGB(r,g,b);
          }

          // Display the colors we just set on the actual LEDs
      delay(wait_time);
      LEDS.show();
      }

    //into yellow
      for( int colorStep=255; colorStep >= 0; colorStep-- ) {

          int r = 255;
          int g = colorStep;
          int b = 0;

          // Now loop though each of the LEDs and set each one to the current color
          for(int x = 0; x < LED_COUNT; x++){
              leds[x] = CRGB(r,g,b);
          }

          // Display the colors we just set on the actual LEDs
      delay(wait_time);
      LEDS.show();
      }

    } //end main loop


body: I have been looking for a good way to play sounds using an Arduino.  I started to consider just buying a cheap mp3 player and replacing the player's buttons with optical switches, which connect to an Arduino.  I wanted to know if anyone has done this before and if there was a good mp3 player for this (one that may have some sort of control port / ir sensor.)

title: Connect an mp3 player to an Arduino?

Answers: 1

body: Yes, people have done this before, and they have documented it on their own blogs and similar sites.  Maybe you should have asked Google first before you came here?  You'd most likely have ended up on [instructables, where someone has documented exactly what you want to do and how to do it.](http://www.instructables.com/id/MP3-Interface-for-Arduino-Cheap-and-Easy/) and saved yourself this entire step.


body:
I have a strip of 7 leds. its ws2812. Im starting them on blue. Next I want them to do a slow fade into pink. So all Im trying right now is to increment r.

I can get them to work one by one. But I need them to all fade together from blue to pink.

Ive moved my r++ loop around till I was cross-eyed. Still it didnt fade all 7 leds to pink all at once.

sometimes it would stay blue and do nothing sometimes fade to pink one pixel at a time.

How do I get all 7 leds to fade together?
Thank you.

    #include <FastLED.h>
    #define NUM_LEDS 7
    #define DATA_PIN 6
    #define BRIGHTNESS 45
    #define COLOR_ORDER GRB
    #define g 50
    #define b 100

    int r; //changed it to undefined

    CRGB leds[NUM_LEDS];

    void setup(){
    FastLED.addLeds<WS2812, DATA_PIN, GRB>(leds, NUM_LEDS);

     }
    void loop(){

this lights all leds to blue

      for(int x = 0; x < NUM_LEDS; x++){

      leds[x] = CRGB(r,g,b);
     }
      FastLED.show();
      delay(10);

this code should grab all 7 leds in NUM_LEDS store it in x

      for(int x = 0; x < NUM_LEDS; x++){

      leds[x] = CRGB(r,g,b);

Heres the problem area. I get no errors but it doesnt fade all 7 leds at a time.
Ive tried moving my code around but it either doesnt fade or fades to pink one led at a time. where should my 'for loop' for incrementing r be at?
Should I be changing rgb all at once using array?

    //take r and fade it up to 254

    for(int r = 0; r < 254; r++) {

      }
      }
         FastLED.show();
     delay(100);

    }

title: fading colors on a ws2812 strip

Answers: 2

body:
If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...

    #include <FastLED.h>
    #define DATA_PIN 6
    #define NUM_LEDS 7

    #define COLOR_ORDER GRB

    CRGB leds[NUM_LEDS];

    void setup(){
      FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

    }

    void loop(){

      // Let's take 256 steps to get from blue to red
      // (the most possible with an LED with 8 bit RGB values)

      for( int colorStep=0; colorStep<256; colorStep++ ) {

          int r = colorStep;  // Redness starts at zero and goes up to full
          int b = 255-colorStep;  // Blue starts at full and goes down to zero
          int g = 0;              // No green needed to go from blue to red

          // Now loop though each of the LEDs and set each one to the current color

          for(int x = 0; x < NUM_LEDS; x++){
              leds[x] = CRGB(r,g,b);
          }

          // Display the colors we just set on the actual LEDs
          FastLED.show();

          delay(10);
      }

    }

body:
@bigjosh has provided code, so I will provide some plain text logic to explain what you should be doing.

To fade from one color to the next, in this case from Solid Blue (0,0,255) to Pink (Red + Blue, 255,0,255), you need to change the value a little, latch it, then wait before you change the value again. Pseudo code:

> rgb = 0,0,255
>
> write rgb
>
> wait X milliseconds
>
> rgb = r + 1,0,255
>
> write rgb
>
> wait X milliseconds
>
> loop until r = 255

At each step, you need to push out the value to the leds before delaying and then starting again. The delay can and should be varied to your satisfaction. I find a fast fade better. At single steps of r + 1, even slow delays will seem mostly smooth.


body:
![enter image description here][1]

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

What the two yellow cables as you can see in the picture do not know?

title: Motor Shield StepMotor

Answers: 1

body:
There are two types of stepper motors: unipolar and bipolar. Bipolars usually have four wires and unipolars have six.

> [![][1]][1]
>
>--http://hobbymilling.com/wp-content/uploads/2011/05/Unipolar-stepper-motor-windings.png
>
> ![](https://www.codeproject.com/KB/system/steppermotorcontrol/pic6.jpg)
>
>--https://www.codeproject.com/KB/system/steppermotorcontrol/pic6.jpg

The motor shield is designed to drive a bipolar motor (4 wires) but the motor is unipolar (6 wires). As you can see in the pictures, if you ignore the middle wire of the unipolar motor, it is the exact same as a bipolar stepper motor.
 [1]: https://i.stack.imgur.com/1Mi9t.png


body:
I need to power an enclosed Arduino Fio project with 12V. The intention is not to attach a battery because there is no need as this is a fixed installation with a 12V DC available (for a pair of relays which will be controlled by the Fio).

My question is what Pins should I use. The Fio page (https://www.arduino.cc/en/Main/ArduinoBoardFio) on the Arduino web site says...

Input Voltage 3.35 -12 V
Input Voltage for Charge 3.7 - 7 V

Unfortunately, there is no indication what pins these specs refer to. I assume that the "Input Voltage for Charge" refers to the mini-USB port and unlike other Arduino boards, there is no Vin pin to supply the board externally. Looking at the board layout on the same web page, I think the only possible option is via the two pins in parallel to the battery port which I suppose are then going into the voltage regulator on the board.

Any comments or suggestions? Has anyone done something similar?

title: What pins to use to externally power an Arduino Fio (without battery)

Answers: 1

body: I used the external switch input JP7-1 for 12v, any GND hole, and make sure the switch is off.  This bypasses the charge circuit which doesn't like 12v.


body:
I am looking for an inexpensive single board computer that I could program in assembly language, using limited facilities to load the object code from a PC and simple I/O peripherals.

Ideally I would like to be able to write in a reasonable time all the code on the machine myself. I don't want an OS in the way, as I want to have a program that writes in RAM some code and then branches to execute it.
Arduino would probably be my best choice, as far as system simplicity suitable for assembly programming goes, but it has a Harvard architecture and it won't allow me to execute from RAM.

Years ago I was using a Von Neumann architecture 8-bit CPU that could branch execution to any address, no matter whether it was mapped to ROM, RAM or whatever. This is what I would like to do now.

I probably could write and load in Flash memory an interpreter of op codes written in RAM, but it is a very complex and time-consuming solution, unless virtual machines of this kind exist already.

Any suggestions on other workarounds with Arduino or of other micro-controllers I might use?

Thanks!

Pierre

title: Is there any way to run binary code from RAM?

Answers: 1

body:
In my opinion the interpreter idea is much more feasible. The notion of writing, in assembler, code that itself generates machine code, in RAM, and then executes it, is itself incredibly complex.

You haven't said why you want to do this, so this is somewhat of an [X-Y problem](http://xyproblem.info/).

>  I don't want an o.s. in the way ...

The normal Arduinos do not have an OS in the way - basically the code you write is what gets loaded onto the chip.


body:
I'm working on wireless uploader for Arduino from iOS devices. I'm using HM-10 BLE module which seems to work ok. PIO 2 is used as DTR for resetting (see `A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 1 [0x31]` and `A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 0 [0x30]` below)- using 0.1uF capacitor and 10K resistor wired to MCU reset pin. Reset seems to be done correctly as i'm getting `ready` output (in 'setup()' body in uploaded sketch).

For some reason i'm getting `0x14 0x10` for `0x30 0x20` request (to ping bootloader) but not getting response for `A [0x41] . [0x81]   [0x20]` within almost 1 second.

Uploading over BLE:

    2015-07-04 19:24:10.955 xctest[54864:5122867] [TRACE  ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 1 [0x31]
    2015-07-04 19:24:10.955 xctest[54864:5122867] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 8
    2015-07-04 19:24:11.106 xctest[54864:5122867] [DEBUG  ] [OUT]: Sending 8 bytes
    2015-07-04 19:24:11.106 xctest[54864:5122867] [TRACE  ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 0 [0x30]
    2015-07-04 19:24:11.106 xctest[54864:5122867] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 8
    2015-07-04 19:24:11.148 xctest[54864:5122867] [DEBUG  ] [   ]: Draining for 230 ms ...
    2015-07-04 19:24:11.148 xctest[54864:5122867] [TRACE  ] [IN ]: Start reading
    2015-07-04 19:24:11.323 xctest[54864:5122903] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
    2015-07-04 19:24:11.323 xctest[54864:5122903] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
    2015-07-04 19:24:11.381 xctest[54864:5122867] [TRACE  ] [IN ]: Finish reading
    2015-07-04 19:24:11.381 xctest[54864:5122867] [TRACE  ] [IN ]: Ble clear buffer
    2015-07-04 19:24:11.381 xctest[54864:5122867] [DEBUG  ] [IN ]: Drained 18 bytes
    2015-07-04 19:24:11.381 xctest[54864:5122867] [DEBUG  ] [OUT]: Sending 2 bytes
    2015-07-04 19:24:11.381 xctest[54864:5122867] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
    2015-07-04 19:24:11.382 xctest[54864:5122867] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
    2015-07-04 19:24:11.382 xctest[54864:5122867] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-07-04 19:24:11.382 xctest[54864:5122867] [TRACE  ] [IN ]: Start reading
    2015-07-04 19:24:11.746 xctest[54864:5122914] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
    2015-07-04 19:24:11.747 xctest[54864:5122914] [TRACE  ] [IN ]: Ignoring single 0x00 char
    2015-07-04 19:24:11.747 xctest[54864:5122914] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
    2015-07-04 19:24:11.748 xctest[54864:5122867] [TRACE  ] [IN ]: Finish reading
    2015-07-04 19:24:11.748 xctest[54864:5122867] [TRACE  ] [IN ]: Receive: . [0x14]
    2015-07-04 19:24:11.749 xctest[54864:5122867] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
    2015-07-04 19:24:11.749 xctest[54864:5122867] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
    2015-07-04 19:24:11.749 xctest[54864:5122867] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-07-04 19:24:11.750 xctest[54864:5122867] [TRACE  ] [IN ]: Having current receive buffer: . [0x10]
    2015-07-04 19:24:11.750 xctest[54864:5122867] [TRACE  ] [IN ]: Start reading
    2015-07-04 19:24:11.750 xctest[54864:5122867] [TRACE  ] [IN ]: Finish reading
    2015-07-04 19:24:11.751 xctest[54864:5122867] [TRACE  ] [IN ]: Receive: . [0x10]
    2015-07-04 19:24:11.751 xctest[54864:5122867] [DEBUG  ] [IN ]: Read 1 bytes, actually received 1 bytes
    2015-07-04 19:24:11.751 xctest[54864:5122867] [TRACE  ] [IN ]: Ble clear buffer
    2015-07-04 19:24:11.752 xctest[54864:5122867] [DEBUG  ] [OUT]: Sending 3 bytes
    2015-07-04 19:24:11.752 xctest[54864:5122867] [TRACE  ] [OUT]: Send: A [0x41] . [0x81]   [0x20]
    2015-07-04 19:24:11.752 xctest[54864:5122867] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
    2015-07-04 19:24:11.752 xctest[54864:5122867] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-07-04 19:24:11.753 xctest[54864:5122867] [TRACE  ] [IN ]: Start reading
    2015-07-04 19:24:11.821 xctest[54864:5122914] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
    2015-07-04 19:24:11.821 xctest[54864:5122914] [TRACE  ] [IN ]: Ignoring single 0x00 char
    2015-07-04 19:24:12.721 xctest[54864:5122903] [TRACE  ] [IN ]: Rx value received 5 bytes: r [0x72] e [0x65] a [0x61] d [0x64] y [0x79]
    2015-07-04 19:24:12.722 xctest[54864:5122867] [TRACE  ] [IN ]: Finish reading
    2015-07-04 19:24:12.722 xctest[54864:5122867] [TRACE  ] [IN ]: Receive: r [0x72]
    2015-07-04 19:24:12.723 xctest[54864:5122867] [DEBUG  ] [IN ]: Read 1 bytes, actually received 5 bytes
    2015-07-04 19:24:12.723 xctest[54864:5122867] [TRACE  ] [IN ]: 4 bytes in incoming buffer remaining for next receive
    2015-07-04 19:24:12.723 xctest[54864:5122867] [ERROR  ] [   ]: STK500:getParameter: protocol error #1, expected [0x14], received [0x72]

When uploading over usb it's ok:

    2015-06-29 16:34:10.829 xctest[36585:3703900] [TRACE  ] [   ]: DTR/RTS supported by Serial, resetting
    2015-06-29 16:34:11.140 xctest[36585:3703900] [DEBUG  ] [IN ]: Draining ...
    2015-06-29 16:34:11.392 xctest[36585:3703900] [DEBUG  ] [IN ]: Drain done
    2015-06-29 16:34:11.392 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 2 bytes
    2015-06-29 16:34:11.392 xctest[36585:3703900] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
    2015-06-29 16:34:11.393 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.531 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
    2015-06-29 16:34:11.531 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.532 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
    2015-06-29 16:34:11.532 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 3 bytes
    2015-06-29 16:34:11.532 xctest[36585:3703900] [TRACE  ] [OUT]: Send: A [0x41] . [0x81]   [0x20]
    2015-06-29 16:34:11.533 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.535 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
    2015-06-29 16:34:11.536 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.536 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x04]
    2015-06-29 16:34:11.536 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.536 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
    2015-06-29 16:34:11.537 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 3 bytes
    2015-06-29 16:34:11.537 xctest[36585:3703900] [TRACE  ] [OUT]: Send: A [0x41] . [0x82]   [0x20]
    2015-06-29 16:34:11.537 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.540 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
    2015-06-29 16:34:11.540 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.540 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x04]
    2015-06-29 16:34:11.540 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.541 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
    2015-06-29 16:34:11.541 xctest[36585:3703900] [DEBUG  ] [   ]: STK500:initialize: n_extparms = 4
    2015-06-29 16:34:11.541 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 22 bytes
    2015-06-29 16:34:11.542 xctest[36585:3703900] [TRACE  ] [OUT]: Send: B [0x42] . [0x86] . [0x00] . [0x01] . [0x00] . [0x01] . [0x01] . [0x01] . [0x03] . [0xFF] . [0xFF] . [0xFF] . [0xFF] . [0x00] . [0x80] . [0x04] . [0x00] . [0x00] . [0x00] . [0x80] . [0x00]   [0x20]
    2015-06-29 16:34:11.542 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.548 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
    2015-06-29 16:34:11.548 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.548 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
    2015-06-29 16:34:11.548 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 7 bytes
    2015-06-29 16:34:11.549 xctest[36585:3703900] [TRACE  ] [OUT]: Send: E [0x45] . [0x05] . [0x04] . [0xD7] . [0xC2] . [0x00]   [0x20]
    2015-06-29 16:34:11.549 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.552 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
    2015-06-29 16:34:11.552 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.552 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
    2015-06-29 16:34:11.553 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 2 bytes
    2015-06-29 16:34:11.553 xctest[36585:3703900] [TRACE  ] [OUT]: Send: P [0x50]   [0x20]
    2015-06-29 16:34:11.553 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.556 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
    2015-06-29 16:34:11.556 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
    2015-06-29 16:34:11.556 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
    2015-06-29 16:34:11.569 xctest[36585:3703900] Reading |                                                    | 0% 0ms
    2015-06-29 16:34:11.570 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 2 bytes
    2015-06-29 16:34:11.571 xctest[36585:3703900] [TRACE  ] [OUT]: Send: u [0x75]   [0x20]
    2015-06-29 16:34:11.571 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 5 bytes
    2015-06-29 16:34:11.572 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14] . [0x1E] . [0x95] . [0x0F] . [0x10]
    2015-06-29 16:34:11.572 xctest[36585:3703900] Reading | ################################################## | 100% 2ms

So when uploading over USB DTR/RTS and [similar schematic][1] is used.

I think the problem is in resetting approach - wiring to reset does not work when trying to upload. Am i right? Is it bootloader issue?

PS. Arduino sketch uploaded:
<!-- language-all: lang-cpp -->

    void setup() {
      Serial.begin(115200);
      Serial.print("ready");

      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

  [1]: https://electronics.stackexchange.com/questions/61537/what-is-the-cap-for-in-arduino-reset-circuit

title: Arduino not responding while trying to flash over BLE

Answers: 0


body:
I have programmed Attiny88 with Arduino IDE 1.6.5 using https://github.com/SpenceKonde/ATTinyCore . I chose Attiny88 because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins with dedicated SPI.  I wrote a code for arduino to work as SPI master, and a code for Attiny88 as SPI slave but I get only 0 as answer from Attiny.

SPI master code for ARduino UNO

    #include <SPI.h>

    // set up the speed, data order and data mode
    SPISettings settingsA(2000000, MSBFIRST, SPI_MODE0);
    const int slaveAPin = 10;

    void setup() {
      // set the Slave Select Pins as outputs:
      Serial.begin(9600);
      Serial.println("SPI ON");
      pinMode (slaveAPin, OUTPUT);
      SPI.begin();
    }

    uint8_t stat, val1, result;

    void loop() {
       // read two bytes from device A
       SPI.beginTransaction(settingsA);
       digitalWrite (slaveAPin, LOW);
       // reading only, so data sent does not matter
      stat = SPI.transfer(0);
      val1 = SPI.transfer(0);
      digitalWrite (slaveAPin, HIGH);
      SPI.endTransaction();
      Serial.println("data");
      Serial.println(stat);
      Serial.println(val1);
      Serial.println("end");
      SPI.endTransaction();
      delay(300);
    }

SPI slave code for Attiny88:

    #include <SPI.h>

    // set up the speed, data order and data mode
    SPISettings settingsA(2000000, MSBFIRST, SPI_MODE0);
    const int slavePin = 14;
    const int ledPin = 9;

    uint8_t stat, val1, val2, result;

    void setup() {
      // set the Slave Select Pins as outputs:
      pinMode (slavePin, INPUT);
      pinMode (ledPin, OUTPUT);
      // initialize SPI:
      digitalWrite(ledPin, HIGH);
      delay(1000);
      SPI.begin();
      stat =128;
      val1= 1;
    }

    void loop() {

      if (slavePin==LOW) {
        SPI.beginTransaction(settingsA);
        SPI.transfer(stat);
        SPI.transfer(val1);
        result = SPI.transfer(0);
        digitalWrite(ledPin, result);
        SPI.endTransaction();
      }

    }

title: Attiny88 as SPI slave

Answers: 1

body:
You do not appear to be configuring the slave as an SPI slave. Merely changing the pin modes won't achieve this. Example code at [SPI - Serial Peripheral Interface - for Arduino](http://www.gammon.com.au/spi) - however that does not specifically mention the Attiny88.

In my example in reply #1 on that page I have this code:

      // turn on SPI in slave mode
      SPCR |= bit (SPE);

      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);

This sets SPCR bit MSTR to zero (by not mentioning it). If you call SPI.begin() it will be activated in **master** mode.

It looks like the Attiny88 has the same register.

So in my opinion your code merely has two SPI masters.

Also, you seem to be doing 3 transfers in the master, but only 2 transfers in the slave.


body:
I am looking for a way to protect my Arduino's digital outputs from unwanted, outside voltages. My project uses about 20 different outputs, each connected to a wire (run) that can range from 20 to 100 feet (I used cat5 cable, with each inner wire (randomly chosen) dedicated to a single digital in, out, +5, +9 or ground.)  There is a good change that outside voltages could impact these digital outs (or any other pin or power wire.)

I have a good resource on protecting digital in's but I ma not sure how to protect the digital outs.  Each needs to be able to both pull a connect component to ground, and push it up to 5 volts (am I saying this correctly?)

This should be able to protect the digital outs from shorts or 12v spikes.

How can I build this circuit?

Edit: it is difficult for me to describe this problem without mentioning the danger to all components.

Note that ways of protecting digital *inputs* is [HERE][1].

  [1]: https://arduino.stackexchange.com/questions/13126/best-way-to-protect-a-digital-or-analog-input-from-12volts/13128?noredirect=1#comment23597_13128

title: Best way to protect a digital output?

Answers: 4

body:
Add a resistor in the circuit to limit the current in case of a short.

Add clamping diode to prevent voltages higher than 5v (combined with the resistor from before). The AVR has internal clamping diodes, but those can only handle very little current. Since you are running such long wires, you probably need to add the lowest value resistor, to limit noise.

PS The possibility of have a external voltage applied to an output sound pretty troubling to me.

body:
Some good results you can get with [optocouplers][1].
[![PC817 photo][2]][2]

It's electrically disconnects one part of your circuit from another.

For example, here is my IoT-ish device, which is detects water leaks in my bathroom:
[![Scheme][3]][3]

I use the transformer (T1), which have two separate output windings, so, that windings does not connected electrically, only magnetically. The block in border "Sensing unit" doesn't have any wires with other scheme - only magnetic field, which is gives it power, and infrared light in the optocoupler (u2, [PC817][4]), which informs ESP01 about leak presence.

How does it work? Very simple! When the water shorts JP1 (long naked wires on the floor), Q1 opens and lights-up the IR diode in PC817. Light from this diode opens another transistor - and pulls the RxD PIN of ESP01 down.

[Small sketch][5], written on Arduino for ESP8266 periodically sends pin state by `HTTPS` on my web server, where monitor software, [Nagios][6], checks the information age and the pin state, and send to me notifications, when something goes wrong.

  [1]: https://en.wikipedia.org/wiki/Opto-isolator
  [2]: https://i.stack.imgur.com/4OV9U.png
  [3]: https://i.stack.imgur.com/CPr45.png
  [4]: https://pdf1.alldatasheet.com/datasheet-pdf/view/43368/SHARP/PC817.html
  [5]: https://github.com/BG4444/waterLeakDetector
  [6]: https://en.wikipedia.org/wiki/Nagios

body: Check with your favorite automotive semiconductor supplier such as ST. In there automotive listings you will find drivers that will do exactly what you want and if shorted to long will shut down and come back when the short is removed.  I am not going to make a recommendation as there are literally hundreds of possibilities. These come from 1 driver per unit to 8 that would be easy to purchase. They have parallel and serial interfaces depending on what you want. If you want to be nasty get a 50 amp driver and put a huge power supply behind it, then enjoy the looks and smoke when shorted and you get the last laugh your Arduino will be OK.  Have Fun!

body:
See [10 Ways to Destroy An Arduino](http://www.rugged-circuits.com/10-ways-to-destroy-an-arduino)

One of the suggestions there for output pins was:

> Put a 30mA resettable fuse (PTC) in series with every I/O pin. Not only is the current safely limited to 30mA under all conditions (more on this below), but the built-in 220 ohm resistance of the fuse naturally limits the current to 5V/220 = 23mA right off the bat.

You may also want to look at some of the suggestions on [the question about protecting input pins](https://arduino.stackexchange.com/questions/13126/) which could help with keeping spikes out of the output circuits.


body:
I'd like to send sensor values over ethernet shield to a webserver. But for this I'd like to encrypt the data on the arduino and decrypt it on the webserver (PHP).
Do you have any suggestions or examples?

title: Encrypting data for webserver

Answers: 1

body:
XTEA is probably your best bet.  It's lightweight, easy to implement, and secure enough for a bit of sensor data...

* https://en.wikipedia.org/wiki/XTEA

There's also the slightly more complex, and also slightly more secure, XXTEA:

* https://en.wikipedia.org/wiki/XXTEA


body:
I work in a robot using arduino, and i have a few questions:
It is possible to increase the speed of a servo, for example a parallax?
It is possible to measure the current that pass through a servo?

title: Servo Speed Control

Answers: 2

body:
The speed of most servos cannot be changed in your code (unless your code is limiting the speed by changing the position in small increments with long delays between your writes). Most servos, in my experience, try to get to the set position as fast as the physical motors can possibly move while keeping the motion somewhat motors. However, motors can only go so fast, so you are limited.

One thing to note: some servo motors can be powered at higher voltages, but still controlled at 5V. With the increase in voltage, it might allow the motor to go a little faster, although the results will vary based on the servo's electrical characteristics and the motor driver's algorithm.

As for the current, you can buy cheap current sensors online that can be interfaced with the Arduino. You will want to measure the current (in series) flowing either from your power source to the VCC of the stepper, or from the GND of the stepper back to the GND of your Arduino.

body:
Part 1: Can I increase the speed of the servo motor?
====================================================
Solution #1 :
----------
You can run your servo motor at its maximum rated voltage, which will give you the fastest response. If angle is all you want, that should be ok.

Solution #2 :
-------------
If speed control is just as important, you're better off using a [DC motor with an encoder][1]. You will have to write a PI control loop, but in return you will be granted a fine-tune control and potentially superior performance.

Solution #3 :
-------------
If you need to hold a physical load accurately at a certain angle, then I would go for a [stepper motor][2]. But you need to make sure that you do not overload it, as it will cause a misstep.

Part 2: Can I measure the current?
====================================================
The simplest and cheapest method, is to connect a current sensing resistor to your servo and measure the potential difference using the analog input. Since the resistance is known, you can calculate the current using the formula I = V/R.

Two things to make sure:
1) Your resistor power rating is not exceeded.
2) The voltage difference has to be large enough to be measurable. (e.g. 2 ohm resistor gives .05V @ 100mA, .5V @ 1A and your Arduino analog input may have the resolution of roughly 0.005V)

What? Did I hear you say that the accuracy isn't good enough? Well actually you can buy an op amp to amplify to the scale that you need. Or to make life easier: buy one from [Adafruit][3]. :p

Hope this helps.

  [1]: https://www.parallax.com/product/28819
  [2]: http://www.adafruit.com/products/324
  [3]: https://www.adafruit.com/products/904


body:
I'm working on a Arduino controlled solenoid motor project that I found on Instructables. I have been able to piece together what I think is most of the code but I'm getting some syntax errors and was wondering if I could get some help? Here is the code and the errors.

       // Including Libraries
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <math.h>

    LiquidCrystal_I2C mydisplay(0x27,16,2);

    // Define Input/Output Pins
    #define solenoidpin 9
    #define potpin 1
    #define ignitioninputpin 2
    ///#define interruptnumber 3
    #define isr_rpm(INT0_vect)

    // Defineing Variables
     int previousstate;
     byte buttonstate;
     int counter1;
     int start;
     int finish;
     int elapsed;
     int RPM;

    // Main setup
    void setup(){
      pinMode(ignitioninputpin,INPUT);
      digitalWrite(ignitioninputpin,HIGH);
    ////  attachInterrupt(3,isr_rpm, FALLING);
      counter1=1;

      mydisplay.init();
      mydisplay.backlight();
      mydisplay.setCursor(0,1);
      mydisplay.print(" Soleniod Motor ");

      previousstate=HIGH;
      Serial.begin(19200);
      buttonstate = digitalRead(ignitioninputpin);
    }

    // Main program loop
    void loop() {
      buttonstate = digitalRead(ignitioninputpin);
      Serial.println(buttonstate);
      Serial.write("previousstate");
      Serial.println(previousstate);
      Serial.println(counter1);
      float elapsed=start=finish;
      float RPM= (6000/elapsed);
    {

    if  (buttonstate==LOW && previousstate==HIGH && (counter1%2)==0){
        digitalWrite(solenoidpin,HIGH);
      }

    if  (buttonstate==HIGH && previousstate==LOW && (counter1%2)==0){
        digitalWrite(solenoidpin,HIGH);
      }

    if  (buttonstate==LOW && previousstate==HIGH && (counter1%2)==0){
        digitalWrite(solenoidpin,LOW);
      }

    if  ((counter1%2)==0){                                            for rpm calcs
        finish=start;
        start=millis();
      }

    if  ((counter1%6)==0){
        mydisplay.setCursor(0,0);
        mydisplay.print(" RPM ");
        mydisplay.print(RPM);
        mydisplay.setCursor(0,1);
        mydisplay.print(" Solenoid Motor ");
      }

    void ISR1();
      buttonstate=LOW;
      counter1=counter1+1;
      previousstate=HIGH;
      }
     }

Error messages:

Binary sketch size: 7,594 bytes (of a 32,256 byte maximum)

title: coding problems

Answers: 2

body:
Welcome to Arduino.SE. I am not going to rewrite the code for you but from this and other answers and comments you should be able to correct the code for yourself from constructive criticism.

To start at the beginning.
You have defined `interruptpinnumber` but you don't use it in the `attachInterrupt` function as you declare interrupt pin 1(digital pin 3) and not 0 as the interrupt pin, this will cause problems in your code.

Next, for your timing variables, they need to be `unsigned long` as the `millis()` function will return unsigned long. There is also no need to declare them volatile as you are not using them in the ISR routine.

On the topic of the ISR, you have used the arduino [attachInterrupt()][1] and you have used the actual `ISR()` [routine from the AVR libraries][2], also without including it. In the ISR you need to give it a vector which is not there and that is going to give errors later on. You also do not need the ISR routine if you have used the function from Arduino. You need to ensure that what you declare as the routine( that being `isr_rpm`) in the `attachInterrupt()` function to be executed when the interrupt occurs, actually exists.

Also there are some basic arithmetic issues with the `elapsed` time calculation, that is if you were trying to determine the difference.

As @Majenko also pointed out and I was going to too, that the use of a bitwise AND, `&` in your `if()` statements might not be a problem but best to learn now that you should use logical AND for comparison `&&`.

There is also a redundant `if` statement, that I will leave to you to find as it is your code and you can determine if it is of use or not. Also you need to keep track of you braces as this will cause the errors you are seeing too.

***Edit***

I think I need to elaborate on a few things as I think you got confused a bit more.

Concerning the whole arduino attachInterrupt function, the `isr_rpm()` needs to be a function and not a define, I think this caused it

>! In the ISR you need to give it a vector which is not there and that is going to give errors later on. You also do not need the ISR routine if you have used the function from Arduino. You need to ensure that what you declare as the routine( that being `isr_rpm`) in the `attachInterrupt()` function to be executed when the interrupt occurs, actually exists.

 A function of that would be:

    void isr_rpm(){

       //code

    }

As @Majenko has kindly done you a favor and annotated your code, look at the stuff *related to the interrupt routine* (and other stuff) and compare it with the below avrfreaks tutorial, and the original code if you have it, the problem to begin with was that you had *too many braces*:

    void ISR(){
          buttonState = LOW;
          counter1 = counter1 + 1;
          previousState = HIGH;
        }
        }

it should be:

    ISR(INT0_vect){
          buttonState = LOW;
          counter1 = counter1 + 1;
          previousState = HIGH;
        }

There is no need to give your own special name to ISR either, this is from the newer code.

[AVRfreaks tutorial concerning interrupts and the ISR stuff][3] it will give you an explanation on the volatile stuff too.

I cannot stress the point more but, look through your code that Majenko has annotated and see where you can fix the code.

  [1]: https://www.arduino.cc/en/Reference/attachInterrupt
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html
  [3]: https://www.avrfreaks.net/forum/tut-newbies-guide-avr-interrupts?page=all

body:
Ok, I swore I wasn't going to do this, but I have re-formatted your latest code and I am going to go through and annotate it.

    // Including Libraries
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <math.h>  /// << WHY?!  You're not using it!

    LiquidCrystal_I2C mydisplay(0x27, 16, 2);

    // Define Input/Output Pins
    #define solenoidpin 9
    #define potpin 1
    #define ignitioninputpin 2
    ///#define interruptnumber 3
    #define isr_rpm(INT0_vect)  /// << What is this hoping to achieve?

    // Defineing Variables
    int previousstate;
    byte buttonstate;
    int counter1;
    int start;  ///
    int finish; /// << These should be unsigned long
    int elapsed;///
    int RPM;

    // Main setup
    void setup() {
     pinMode(ignitioninputpin, INPUT);
     digitalWrite(ignitioninputpin, HIGH);
     ////  attachInterrupt(3,isr_rpm, FALLING);  /// << This will never work with that #define I pointed out...
     counter1 = 1;
     mydisplay.init();
     mydisplay.backlight();
     mydisplay.setCursor(0, 1);
     mydisplay.print(" Soleniod Motor ");
     previousstate = HIGH;
     Serial.begin(19200);
     buttonstate = digitalRead(ignitioninputpin);
    }

    // Main program loop
    void loop() {
     buttonstate = digitalRead(ignitioninputpin);
     Serial.println(buttonstate);
     Serial.write("previousstate");
     Serial.println(previousstate);
     Serial.println(counter1);
     float elapsed = start = finish;  /// << You already defined these as ints in the global
     float RPM = (6000 / elapsed);    /// << scope. Why are you defining them again as floats?!  Also,
                                         /// << elapsed = start = finish?!?!  I think you have an = instead of a -
     { /// << Why are you starting a new block here???
      if (buttonstate == LOW && previousstate == HIGH && (counter1 % 2) == 0) {  /// << counter1 % 2 is very inefficient since counter1 is signed.
       digitalWrite(solenoidpin, HIGH);
      }

      if (buttonstate == HIGH && previousstate == LOW && (counter1 % 2) == 0) { /// << previousstate never changes from HIGH - this will NEVER run!
       digitalWrite(solenoidpin, HIGH);
      }

      if (buttonstate == LOW && previousstate == HIGH && (counter1 % 2) == 0) {  /// << You have already checked this state above with a different outcome.  WHY?!?!
       digitalWrite(solenoidpin, LOW);
      }

      if ((counter1 % 2) == 0) {
       for rpm calcs /// << This isn't even C!!!
       finish = start;

      start = millis();
      }

      if ((counter1 % 6) == 0) {
       mydisplay.setCursor(0, 0);
       mydisplay.print(" RPM ");
       mydisplay.print(RPM);
       mydisplay.setCursor(0, 1);
       mydisplay.print(" Solenoid Motor ");
      }

      void ISR1(); /// << This is a function prototype, not a function definition.
      buttonstate = LOW;       /// << I guess these should be inside
      counter1 = counter1 + 1; /// << a function called ISR1() but that
      previousstate = HIGH;    /// << function hasn't been written.
     }
    }

You're trying to mess around writing low-level interrupt routines without having a clue how to work with low level interrupt routines.  Go back and read the manuals on how to do external interrupts with Arduino.  It's very very simple.

There are things about your program that just make me thing "What?!?!" and things that are just plain missing.


body:
I'm trying to use the Ethernet Shield and the EasyVR (voice recognition) together.
The Ethernet shield uses the same pins that the EasyVR, but the easyVR works fine if I don't call Ethernet.begin(). Is there a way to disconnect the ethernet shield in order to be able to use the EasyVR again?

I haven't seen any method like "release" or "disconnect" in the Ethernet's class.

Thanks!

title: Disconnect Ethernet Shield

Answers: 1

body:
You have correctly determined the root of the problem, both shields are trying to use the same pins. To work around this we need to know which pins are being used, and for what.

The **Ethernet Shield** documentation reveals the following:

> The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

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

The documentation for Sparkfun's EasyVR library isn't as explicit, but one of the examples gives us another clue:

    #if defined(__SAMD21G18A__)
      // Shield Jumper on HW (for Zero, use Programming Port)
      #define port SERIAL_PORT_HARDWARE
      #define pcSerial SERIAL_PORT_MONITOR
    #elif defined(SERIAL_PORT_USBVIRTUAL)
      // Shield Jumper on HW (for Leonardo and Due, use Native Port)
      #define port SERIAL_PORT_HARDWARE
      #define pcSerial SERIAL_PORT_USBVIRTUAL
    #else
      // Shield Jumper on SW (using pins 12/13 or 8/9 as RX/TX)
      #include "SoftwareSerial.h"
      SoftwareSerial port(12, 13);
      #define pcSerial SERIAL_PORT_MONITOR
    #endif

    #include "EasyVR.h"

    EasyVR easyvr(port);

[EasyVR-Arduino/examples/TestEasyVR/TestEasyVR.ino][2]

This block of code is determining how to set up the serial communication. The first two if statements are for different boards, but the third one sets up the software serial connection... and it says there are two options, pins 12/13 OR 8/9! If there are two options, there must be a way to switch it on the board itself.

[![enter image description here][3]][3]

And sure enough! Check out that white box labeled "SW Serial Pins". Jackpot!

Here's what [the manual][4] has to say:

> On the bottom side of the board there are two SMD resistors that you can move to select the two pins of
Arduino that the EasyVR will be connected to when in Software Serial mode (Mode Jumper on SW).
>
> * RX – Software Serial Receiver pin
>     * D12 – Use digital pin 12 as serial receiver (default)
>     * D8 – Use digital pin 8 as serial receiver
> * TX – Software Serial Transmitter pin
>     * D13 – Use digital pin 13 as serial transmitter (default)
>     * D9 – Use digital pin 9 as serial transmitter
>
> The choice of pins 12-13 is maintained for backward compatibility with the previous hardware revisions of
the EasyVR Shield. However those pins may also be used for the SPI interface, so another choice of pins 8-
9 is provided. If you want to use different pins make sure the receiver pin supports change interrupts.

  [1]: https://www.arduino.cc/en/Reference/Ethernet
  [2]: https://github.com/RoboTech-srl/EasyVR-Arduino/blob/d68673fd2e9871fb69e4ff7db30527703f351f0e/examples/TestEasyVR/TestEasyVR.ino
  [3]: https://i.stack.imgur.com/c1i8e.jpg
  [4]: https://www.veear.eu/files/EasyVR 3 User Manual 1.0.16.pdf


body: Is there a way for me to read the pin mode for one of the digital pins on Arduino?   In other words, can I determine whether a pin's been set to an input or output?

title: How to read pinMode for digital pin?

Answers: 3

body:
Yes, you can use the data direction registers (DDR*B*, DDR*C*, DDR*D* depending on which port) to check what mode a pin is in.

If a pin is in output mode then the corresponding bit in DDRx will be 1.

One complication is that the Arduino functions give each pin an "Arduino" pin number, and you have to look at a pin map to figure out which DDR register and bit corresponds to the pin you want to check. You can find a pin map for Arduinos based on the ATMEGA168/ATMEGA328 (including Uno) here...

https://www.arduino.cc/en/Hacking/Atmega168Hardware

So, for example, if you want to check if Arduino digital pin #4 is set for output, you'd look at the map and see that corresponds to PD4. That means "port D" and "bit 4", so you could say...

    if ( DDRD & _BV(4) ) {   // Check bit #4 of the data direction register for port D
        // If we get here, then Arduino digital pin #4 was in output mode
    } else {
        // If we get here, then Arduino digital pin #4 was in input mode
    }

If you want to check Arduino digital pin #14, then you would use `DDRB & _BV(5)`.

*(`_BV(x)` is a macro that shifts `1` `x` bits to the right.)*

body:
There are functions which can get you the registers and bit numbers from a pin number built into the Arduino API.

    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *reg = portModeRegister(port);

    if (*reg & bit) {
        // It's an output
    } else {
        // It's an input
    }

body:
Seems like the Arduino core is missing a function to read the pinMode(). Here is a possible implementation:

    int pinMode(uint8_t pin)
    {
      if (pin >= NUM_DIGITAL_PINS) return (-1);

      uint8_t bit = digitalPinToBitMask(pin);
      uint8_t port = digitalPinToPort(pin);
      volatile uint8_t *reg = portModeRegister(port);
      if (*reg & bit) return (OUTPUT);

      volatile uint8_t *out = portOutputRegister(port);
      return ((*out & bit) ? INPUT_PULLUP : INPUT);
    }

It handles illegal pin numbers (return -1), and all pin modes; OUTPUT, INPUT and INPUT_PULLUP.

Cheers!

BW: I have added this as an [issue][1] on the Arduino github repository.

  [1]: https://github.com/arduino/Arduino/issues/4606


body:
I have investigated the sleeps options of the ATmega328, and read a few articles about it, and I would like to understand if there are more options.

So I would like to get as low current as possible, so that anything less that 100uA would be good - as long as I can listen to uart and interrupts for waking up.

I am using a custom PCB (not the UNO), with ATmega328p.

Setting the chip to deep sleep:

     set_sleep_mode (SLEEP_MODE_PWR_DOWN);
     sleep_enable();
     sleep_cpu ();

would not wake it up with serial communication,according to [this](http://playground.arduino.cc/Learning/ArduinoSleepCode).

You will need to put it in `IDLE` mode, to listen to serial, but this would consume a few mA -bad.

I have found [this link](http://donalmorrissey.blogspot.co.il/2010/04/sleeping-arduino-part-3-wake-up-via.html) where you can connect in hardware the serial to the interrupt - which is dangerous so you can loose data, and moreover, I need these 2 interrupts pins.

I also read [this article of Gammon](http://www.gammon.com.au/forum/?id=11497), where you can disable some things, so you can get IDLE sleep with much lower power - but he didn't mention how exactly you get from this:

     power_adc_disable();
          power_spi_disable();
          power_timer0_disable();
          power_timer1_disable();
          power_timer2_disable();
          power_twi_disable();

So, bottom line, is there any option out there, to get less than 0.25mA at least, and also listen to serial port, without any hardware manipulation?
For example, waking up with **long serial data** input?

title: Put ATmega328 in very deep sleep and listen to serial?

Answers: 2

body:
A board we make does this.

 - The RX pin is wired to INT0
 - INT0 pin set to input or input pullup depending on how the RX line is driven
 - On sleep, INT0 low level interrupt is enabled

        //Clear software flag for rx interrupt
        rx_interrupt_flag = 0;
        //Clear hardware flag for rx interrupt
        EIFR = _BV(INTF0);
        //Re-attach interrupt 0
        attachInterrupt(INT_RX, rx_interrupt, HIGH);

 - INT0 interrupt service routine sets a flag and disables the interrupt

        void rx_interrupt()
        {
            detachInterrupt(INT_RX);
            rx_interrupt_flag = 1;
        }

 - On wakeup, we check for the flag (there are other interrupt sources)

On the comms side of things we use a message protocol that has a start character `>` and end character `\r`. e.g. `>setrtc,2015,07,05,20,58,09\r`. This give some basic protection against losing messages, as incoming characters are not processed until a `>` is received. To wake up the device we send a dummy message before transmission. A single character would do it, but we send `>wakeup\r` hehe.

The device stays awake for 30 seconds after the last message is received in case of new messages. If a new message is receive the 30 second timer is reset. The PC interface software sends a dummy message every second to keep the device awake while the user has it connected for configuration etc.

This method gives absolutely no problems at all. The board with a few peripherals uses about 40uA when sleeping. The actual current consumed by the ATMega328P is probably around 4uA.

**Update**

At look at the datasheet shows that the RX pin is also pin change interrupt pin 16 (PCINT16)

Thus another method without wires may be

 - Before sleep: Set the port change interrupt mask bit in PCMSK2 for PCINT16, clear the pin change port 2 flag in PCIFR, enable the pin change port 2 interrupt (PCINT16-PCINT23) by setting PCIE2 in PCICR.

 - Setup an ISR for the pin change port 2 interrupt and continue as before.

The only caveat with the port change interrupt is that the interrupt is shared across all the 8 pins that are enabled for that port. So if you have more than one pin change enabled for the port, you have to determine which triggered the interrupt in the ISR. This is not a problem if you are not using any other pin change interrupts on that port (PCINT16-PCINT23 in this case)

Ideally this is how I would have designed our board but what we have works.

body:
The code below achieves what you are asking:

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

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

    const byte AWAKE_LED = 8;
    const byte GREEN_LED = 9;
    const unsigned long WAIT_TIME = 5000;

    ISR (PCINT2_vect)
    {
      // handle pin change interrupt for D0 to D7 here
    }  // end of PCINT2_vect

    void setup()
    {
      pinMode (GREEN_LED, OUTPUT);
      pinMode (AWAKE_LED, OUTPUT);
      digitalWrite (AWAKE_LED, HIGH);
      Serial.begin (9600);
    } // end of setup

    unsigned long lastSleep;

    void loop()
    {
      if (millis () - lastSleep >= WAIT_TIME)
      {
        lastSleep = millis ();

        noInterrupts ();

        byte old_ADCSRA = ADCSRA;
        // disable ADC
        ADCSRA = 0;
        // pin change interrupt (example for D0)
        PCMSK2 |= bit (PCINT16); // want pin 0
        PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
        PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7

        set_sleep_mode (SLEEP_MODE_PWR_DOWN);
        power_adc_disable();
        power_spi_disable();
        power_timer0_disable();
        power_timer1_disable();
        power_timer2_disable();
        power_twi_disable();

        UCSR0B &= ~bit (RXEN0);  // disable receiver
        UCSR0B &= ~bit (TXEN0);  // disable transmitter

        sleep_enable();
        digitalWrite (AWAKE_LED, LOW);
        interrupts ();
        sleep_cpu ();
        digitalWrite (AWAKE_LED, HIGH);
        sleep_disable();
        power_all_enable();

        ADCSRA = old_ADCSRA;
        PCICR  &= ~bit (PCIE2);   // disable pin change interrupts for D0 to D7
        UCSR0B |= bit (RXEN0);  // enable receiver
        UCSR0B |= bit (TXEN0);  // enable transmitter
      }  // end of time to sleep

      if (Serial.available () > 0)
      {
        byte flashes = Serial.read () - '0';
        if (flashes > 0 && flashes < 10)
          {
          // flash LED x times
          for (byte i = 0; i < flashes; i++)
            {
            digitalWrite (GREEN_LED, HIGH);
            delay (200);
            digitalWrite (GREEN_LED, LOW);
            delay (200);
            }
          }
      }  // end of if

    }  // end of loop

I used a pin-change interrupt on the Rx pin to notice when serial data arrives. In this test the board goes to sleep if there is no activity after 5 seconds (the "awake" LED goes out). Incoming serial data causes the pin-change interrupt to wake the board. It looks for a number and flashes the "green" LED that number of times.

## Measured current

Running at 5 V, I measured about 120 nA of current when asleep (0.120 µA).

## Awakening message

A problem however is that the first arriving byte is lost due to the fact that the serial hardware expects a falling level on Rx (the start bit) which has already arrived by the time it is fully awake.

I suggest (as in geometrikal's answer) that you first send an "awake" message, and then **pause** for a short time. The pause is to make sure the hardware does not interpret the next byte as part of the awake message. After that it should work fine.

---

Since this uses a pin-change interrupt no other hardware is required.

---

# Amended version using SoftwareSerial

The version below successfully processes the first byte received on serial. It  does this by:

* Using SoftwareSerial which uses pin-change interrupts. The interrupt which is caused by the start bit of the first serial byte also wakes the processor.

* Setting the fuses so that we use:
   * Internal RC oscillator
   * BOD disabled
   * The fuses were: Low: 0xD2, High: 0xDF, Extended: 0xFF

Inspired by FarO in a comment, this lets the processor wake up in 6 clock cycles (750 ns). At 9600 baud each bit time is 1/9600 (104.2 µs) so the extra delay is insignificant.

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

    #include <avr/sleep.h>
    #include <avr/power.h>
    #include <SoftwareSerial.h>

    const byte AWAKE_LED = 8;
    const byte GREEN_LED = 9;
    const unsigned long WAIT_TIME = 5000;
    const byte RX_PIN = 4;
    const byte TX_PIN = 5;

    SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

    void setup()
    {
      pinMode (GREEN_LED, OUTPUT);
      pinMode (AWAKE_LED, OUTPUT);
      digitalWrite (AWAKE_LED, HIGH);
      mySerial.begin(9600);
    } // end of setup

    unsigned long lastSleep;

    void loop()
    {
      if (millis () - lastSleep >= WAIT_TIME)
      {
        lastSleep = millis ();

        noInterrupts ();

        byte old_ADCSRA = ADCSRA;
        // disable ADC
        ADCSRA = 0;

        set_sleep_mode (SLEEP_MODE_PWR_DOWN);
        power_adc_disable();
        power_spi_disable();
        power_timer0_disable();
        power_timer1_disable();
        power_timer2_disable();
        power_twi_disable();

        sleep_enable();
        digitalWrite (AWAKE_LED, LOW);
        interrupts ();
        sleep_cpu ();
        digitalWrite (AWAKE_LED, HIGH);
        sleep_disable();
        power_all_enable();

        ADCSRA = old_ADCSRA;
      }  // end of time to sleep

      if (mySerial.available () > 0)
      {
        byte flashes = mySerial.read () - '0';
        if (flashes > 0 && flashes < 10)
          {
          // flash LED x times
          for (byte i = 0; i < flashes; i++)
            {
            digitalWrite (GREEN_LED, HIGH);
            delay (200);
            digitalWrite (GREEN_LED, LOW);
            delay (200);
            }
          }
      }  // end of if

    }  // end of loop

Power consumption when asleep was measured as 260 nA (0.260 µA) so that is very low consumption when not needed.

Note that with the fuses set like that, the processor runs at 8 MHz. Thus you need to tell the IDE about that (eg. select "Lilypad" as the board type). That way the delays and SoftwareSerial will work at the correct speed.


body:
    char *p = I2CinBuffer; // array contains "string" "," "string"

but

    char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
    char *str;       // Temp store for each data chunk
    int count = 0;

    while ((str = strtok_r(p, ",", &p)) != NULL)    // seperate at each "," delimiter
    {
        inParse[count] = str;      // Add chunk to array
        count++;
    }

does not enter while loop.

Many thanks but the hard coding of the values "6,100" give correct results as it stands. However, I am now aware that the Arduino code is working in C strings and I2CInBuffer is a C string on which the "strtok" or "strok_r" functions will NOT work. My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

title: Array values won't tokenize

Answers: 2

body:
You're not using strtok_r properly.  You have to treat the first call to strtok_r differently to all subsequent calls, and I don't know what you're trying to do with the `&p` parameter - that could never work since you're breaking the source pointer with that.

According to the manual page:

> The strtok_r() function is a reentrant version strtok().  The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.
>
> On  the  first  call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored.  In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

Unless you're doing concurrent tokenising of multiple strings there is no reason to use the reentrant version of strtok.  Instead you should just go:

    char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
    int count = 0;

    char *str = strtok(p, ",");
    while (str != NULL)    // seperate at each "," delimiter
    {
        inParse[count] = str;      // Add chunk to array
        count++;
        str = strtok(NULL, ",");
    }

Note how the first call, outside the while loop, passes the string to parse.  All subsequent calls (inside the while loop) pass `NULL` as the string to parse so it continues from the last point in the string rather than starting the string afresh every time from the start (with a broken string since `strtok()` is a destructive function).

> A sequence of calls to strtok() that operate on the same string maintains a pointer that determines the point from which to start searching for the  next token.   The  first  call  to strtok() sets this pointer to point to the first byte of the string.  The start of the next token is determined by scanning forward for the next nondelimiter byte in str.  If such a byte is found, it is taken as the start of the next token.  If no  such  byte  is  found,  then there are no more tokens, and strtok() returns NULL.  (A string that is empty or that contains only delimiters will thus cause strtok() to return NULL on the first call.)

It is considered *destructive* because:

> The end of each token is found by scanning forward until either the next delimiter byte is found or until the terminating null  byte  ('\0')  is  encountered.   If  a  delimiter byte is found, it is overwritten with a null byte to terminate the current token, and strtok() saves a pointer to the following byte; that pointer will be used as the starting point when searching for the next token.  In this case, strtok() returns a pointer to the  start  of  the found token.

So in other words, your string that started out as:

    foo,bar,baz\0

ends up, after tokenizing, as:

    foo\0bar\0baz\0

So after the first tokenizing, if you try and pass the string again as the first parameter, instead of "foo,bar,baz", it actually only sees "foo" since the string now ends after `foo`.

If you wanted to use the reentrant version you'd need to create a separate pointer variable for the save pointer and pass that as the third argument:

    char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
    int count = 0;
    char *saveptr;

    char *str = strtok_r(p, ",", &saveptr);
    while (str != NULL)    // seperate at each "," delimiter
    {
        inParse[count] = str;      // Add chunk to array
        count++;
        str = strtok(NULL, ",", &saveptr);
    }

Note that you still need to use the same "pass the string on the first call and pass NULL on all other calls" methodology since it is still destructive.

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

>  My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

Example code:

    int parseit (char * p, int * results, const int maxSize)
    {
      int count = 0;
      char *str = strtok (p, ",");   // separate at each "," delimiter
      while (str != NULL && count < maxSize)
        {
        results [count++] = atoi (str);      // Add to array
        str = strtok(NULL, ",");
        }  // end of while
      return count;
    }  // end of parseit

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ();
      const int MAX_INTEGERS = 5;
      int inParse [MAX_INTEGERS];
      char  I2CinBuffer [50];

      strcpy (I2CinBuffer, "6,100");
      int found = parseit (I2CinBuffer, inParse, MAX_INTEGERS);
      for (int i = 0; i < found; i++)
        {
        Serial.print (i);
        Serial.print (" = ");
        Serial.println (inParse [i]);
        }  // end of for

    }  // end of setup

    void loop ()
    {
      // rest of code here
    }  // end of loop

Results from running it:

    0 = 6
    1 = 100


body:
I have no previous experience with C++ or C, but know how to program C# and am learning Arduino. I just want to organize my sketches and am quite comfortable with the Arduino language even with its limitations, but I really would like to have an object-oriented approach to my Arduino programming.

So I have seen that you can have the following ways (not exhaustive list) to organize code:

 1. A single .ino file;
 2. Multiple .ino files in the same folder (what the IDE calls and displays like "tabs");
 3. An .ino file with an included .h and .cpp file in the same folder;
 4. Same as above, but the files are an installed library inside Arduino program folder.

I have also heard of the following ways, but have not got them working yet:

 - Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);
 - __[preferred approach]__ Including a .cpp file where a class is declared, but _without_ using a .h file (would like this approach, should that work?);

Note that I only want to use classes so that code is more partitioned, my applications should be very simple, only involving buttons, leds and buzzers mostly.

title: Classes and objects: how many and which file types do I actually need to use them?

Answers: 3

body:
My advice is to stick to the typical C++ way of doing things: separate interface and implementation into .h and .cpp files for each class.

There are a few catches:

 - you need at least one .ino file - I use a symlink to the .cpp file where I instantiate the classes.
 - you must provide the callbacks that the Arduino environment expects (setu, loop, etc.)
 - in some cases you will be surprised by the non-standard weird things that differentiate the Arduino IDE from a normal one, like automatic inclusion of certain libraries, but not others.

Or, you could ditch the Arduino IDE and try with [Eclipse][1].
As i mentioned, some of the things that are supposed to help beginners, tend to come in the way of more experienced developers.

  [1]: http://www.instructables.com/id/How-to-get-started-with-Eclipse-and-AVR/

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

## How the IDE organizes things

First thing, this is how the IDE organizes your "sketch":

* The main `.ino` file is the one of the same name as the folder it is in. So, for `foobar.ino` in `foobar` folder - the main file is foobar.ino.
* Any other `.ino` files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
* This concatenated file becomes a `.cpp` file (eg. `foobar.cpp`) - it is placed in a temporary compilation folder.
* The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
* The main file is scanned for `#include <libraryname>` directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
* Any `.c`, `.cpp` or `.asm` files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
* Any `.h` files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
* The compiler adds into the build process standard files (like `main.cpp`)
* The build process then compiles all the above files into object files.
* If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you `strcpy` etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.

---

## Avoiding the pre-processor quirks

The simplest way of avoiding these idiosyncrasies is to leave your main sketch blank (and not use any other `.ino` files). Then make another tab (a `.cpp` file) and put your stuff into it like this:

    #include <Arduino.h>

    // put your sketch here ...

    void setup ()
      {

      }  // end of setup

    void loop ()
      {

      }  // end of loop

Note that you need to include `Arduino.h`. The IDE does that automatically for the main sketch, but for other compilation units, you have to do it. Otherwise it won't know about things like String, the hardware registers, etc.

---

## Avoiding the setup/main paradigm

You don't have to run with the setup/loop concept. For example, your .cpp file can be:

    #include <Arduino.h>

    int main ()
      {
      init ();  // initialize timers
      Serial.begin (115200);
      Serial.println ("Hello, world");
      Serial.flush (); // let serial printing finish
      }  // end of main

---

## Force library inclusion

If you run with the "empty sketch" concept you still need to include libraries used elsewhere in the project, for example in your main `.ino` file:

    #include <Wire.h>
    #include <SPI.h>
    #include <EEPROM.h>

This is because the IDE only scans the main file for library usage. Effectively you can consider the main file as a "project" file which nominates which external libraries are in use.

---

## Naming issues

* Don't name your main sketch "main.cpp" - the IDE includes its own main.cpp so you will have a duplicate if you do that.

* Don't name your .cpp file with the same name as your main .ino file. Since the .ino file effectively becomes a .cpp file this also would give you a name clash.

---

> Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);

Yes, this compiles OK:

    class foo {
      public:
    };

    foo bar;

    void setup () { }
    void loop () { }

However you are probably best off to follow normal practice: Put your declarations in `.h` files and your definitions (implementations) in `.cpp` (or `.c`) files.

### Why "probably"?

As my example shows you *can* put everything together in one file. For larger projects it is better to be more organized. Eventually you get to the stage in a medium to large-size project where you want to separate out things into "black boxes" - that is, a class that does one thing, does it well, is tested, and is self-contained (as far as possible).

If this class is then used in multiple other files in your project this is where the separate `.h` and `.cpp` files come into play.

* The `.h` file *declares* the class - that is, it provides enough detail for other files to know what it does, what functions it has, and how they are called.

* The `.cpp` file *defines* (implements) the class - that is, it actually provides the functions, and static class members, that make the class do its thing. Since you only want to implement it once, this is in a separate file.

* The `.h` file is what gets included into other files. The `.cpp` file is compiled once by the IDE to implement the class functions.

### Libraries

If you follow this paradigm, then you are ready to move the entire class (the `.h` and `.cpp` files) into a library very easily. Then it can be shared between multiple projects. All that is required is to make a folder (eg. `myLibrary`) and put the `.h` and `.cpp` files into it (eg. `myLibrary.h` and `myLibrary.cpp`) and then put this folder inside your `libraries` folder in the folder where your sketches are kept (the sketchbook folder).

Restart the IDE and it now knows about this library. This is really trivially simple, and now you can share this library over multiple projects. I do this a lot.

---

A bit more detail [here](http://www.gammon.com.au/forum/?id=12625).

body:
I'm posting an answer just for completeness, after finding out and testing a way of declaring _and_ implementing a class in the same .cpp file, without using a header. So, regarding the exact phrasing of my question "how many file types do I need to use classes", the present answer uses two files: one .ino with an include, setup and loop, and the .cpp containing the whole (rather minimalistic) class, representing the turning signals of a toy vehicle.

Blinker.ino

    #include <TurnSignals.cpp>

    TurnSignals turnSignals(2, 4, 8);

    void setup() { }

    void loop() {
      turnSignals.run();
    }

TurnSignals.cpp

    #include "Arduino.h"

    class TurnSignals
    {
        int
            _left,
            _right,
            _buzzer;

        const int
            amberPeriod = 300,

            beepInFrequency = 600,
            beepOutFrequency = 500,
            beepDuration = 20;

        boolean
            lightsOn = false;

        public : TurnSignals(int leftPin, int rightPin, int buzzerPin)
        {
            _left = leftPin;
            _right = rightPin;
            _buzzer = buzzerPin;

            pinMode(_left, OUTPUT);
            pinMode(_right, OUTPUT);
            pinMode(_buzzer, OUTPUT);
        }

        public : void run()
        {
            blinkAll();
        }

        void blinkAll()
        {
            static long lastMillis = 0;
            long currentMillis = millis();
            long elapsed = currentMillis - lastMillis;
            if (elapsed > amberPeriod) {
                if (lightsOn)
                    turnLightsOff();
                else
                    turnLightsOn();
                lastMillis = currentMillis;
            }
        }

        void turnLightsOn()
        {
            tone(_buzzer, beepInFrequency, beepDuration);
            digitalWrite(_left, HIGH);
            digitalWrite(_right, HIGH);
            lightsOn = true;
        }

        void turnLightsOff()
        {
            tone(_buzzer, beepOutFrequency, beepDuration);
            digitalWrite(_left, LOW);
            digitalWrite(_right, LOW);
            lightsOn = false;
        }
    };


body:
 I'm trying to drive a **12v dc motor** using three push buttons, one to turn clockwise, the other counter-clockwise and the other to stop the motor completely.

However the code below is not working, apparently it feels like I'm doing something wrong in the code on the connect buttons on the analog part of the engine shield L293D.

The Arduino is powered by a **9v** battery and **motor shield **L293D** with an external power.

    #include <AFMotor.h>

        AF_DCMotor motor(1);

        int val;

        #define btnleft A0
        #define btncenter A1
        #define btnright A2

        void setup()
        {
          pinMode(btnleft, INPUT);
          analogWrite(btnleft, HIGH);
          pinMode(btncenter, INPUT);
          analogWrite(btncenter, HIGH);
          pinMode(btnright, INPUT);
          analogWrite(btnright, HIGH);
        }

        void loop()
        {
         val=digitalRead(btnleft);
           if(val!=1)
            {
            Serial.print("LEFT: ");
            motor.setSpeed(255);
            motor.run(FORWARD);
            delay(3800);
            }

         val=digitalRead(btncenter);
           if(val!=1)
            {
            Serial.print("CENTER");
            motor.setSpeed(255);
            motor.run(BACKWARD);
            delay(3800);
            }

         val=digitalRead(btnright);
           if(val!=1)
            {
            Serial.print("RIGHT");
            motor.run(RELEASE);
            delay(3000);
            }
        }

title: Triggering the push button on the analog input of the L293D motorshield

Answers: 1

body:
<strike>As noted in Nick Gammon's comment, `digitalWrite(btnleft, INPUT)` (etc.) would make a lot more sense than does `analogWrite(btnleft, INPUT)` (etc.).</strike>

***
*Edit:* `INPUT` is a constant defined in `wiring.h` (as in following extract), and is intended for use in [`pinMode()`](https://www.arduino.cc/en/Reference/PinMode) calls that set an IO pin's mode to one of `INPUT`, `OUTPUT`, or `INPUT_PULLUP`.  It's inept to use it in a call of either [`digitalWrite()`](https://www.arduino.cc/en/Reference/DigitalWrite) or `analogWrite()`.

        #define HIGH 0x1
        #define LOW  0x0
        #define INPUT 0x0
        #define OUTPUT 0x1
        #define INPUT_PULLUP 0x2

***

Note that [`digitalWrite`](https://www.arduino.cc/en/Reference/DigitalWrite) to an input-mode pin leaves the pin in input-mode, while an [`analogWrite`](https://www.arduino.cc/en/Reference/analogWrite) to an input-mode pin changes the pin to output-mode.

When you want a pin to be input-mode with pullup, it is simpler to use `INPUT_PULLUP` as the mode parameter, rather than using two separate calls.  That is, instead of saying [`pinMode(pin, INPUT);`](https://www.arduino.cc/en/Reference/pinMode) followed by `digitalWrite(pin, HIGH);`, just say

    pinMode(pin, INPUT_PULLUP);


body:
I have bought a HC-05 bluetooth module for Arduino.

My requirement is to read data transmitted from iBeacon, is it possible using HC-05 or I have to shift to HM-10?

title: Reading iBeacon Data using HC-05 bluetooth module

Answers: 1

body: The HC-05 doesn't support BLE, which is used for iBeacons.