body:
I think your problem here is that you are using multiple instances of Adafruit_VS1053_FilePlayer.

Namely:

    Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

That's two already.

Then you pass a copy here:

    Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

And return another copy:

    return mp;

All this creating/destroying copies is probably stopping the playback of the current copy.

I've reworked your code to avoid all that:

    #include <Adafruit_VS1053.h>

    // These are the pins used for the music maker shield
    #define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
    #define SHIELD_CS     7      // VS1053 chip select pin (output)
    #define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

    // These are common pins between breakout and shield
    #define CARDCS 4     // Card chip select pin
    // DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
    #define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

    // create shield-example object
    Adafruit_VS1053_FilePlayer musicPlayer (SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

    //global variables required
    boolean crossingSignalInOperation = false;
    boolean signalEntrySensor = false;
    boolean signalExitSensor = false;
    boolean debugMode = false;

    boolean checkEntrySensor() {
        //check entry sensor, if tripped return true otherwise false
        /*if () return true;
        return false;*/
        return true;  //hardcoded for testing
    }

    void setup() {
        // put your setup code here, to run once:
        Serial.begin(9600);
        debugMode = true;   //set this to false once code is fully operational
        //initialise music maker shield
            if (!musicPlayer.begin()) {
                if (debugMode)
                {
                    Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
                }

            while (1);
        }
        // 1st parameter is left, second parameter is right
        musicPlayer.setVolume(20, 20);
        if (debugMode)
        {
            Serial.println(F("VS1053 found"));
        }

        // initialise the SD card
        SD.begin(CARDCS);

        //ensure our global booleans all start false
        crossingSignalInOperation = false;

    }

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

        signalEntrySensor = checkEntrySensor();
        if (signalEntrySensor == true) {  //only want to catch the FIRST time it senses
            if (crossingSignalInOperation == false)
            {
                //crossing signal is inactive, activate it
                // turn the sound on and return the music player object
                onSignalSound(musicPlayer,"trainxng.mp3");

                while (musicPlayer.playingMusic) {
                    // file is now playing in the 'background' so now's a good time
                    // to do something else
                    if (!crossingSignalInOperation)
                    {
                        crossingSignalInOperation = true;
                        //run the other three processes
                        //offRoadPower();
                        //lowerSignalArms();
                        //startSignalFlashers();

                    }
                }
            }
        }
     }

    void onSignalSound(Adafruit_VS1053_FilePlayer & mp, const char* fileName) {
        // Play the train crossing sound file
        if (debugMode)
        {
            Serial.println(F("Playing track - "));
            Serial.print(fileName);
        }
        //all sound files are on the micro sd card on the music player shield
        if (!mp.startPlayingFile(fileName)) {
            Serial.println(F("Could not open file "));
            Serial.print(fileName);
            while (1);
        }
    }
    boolean offSignalSound(Adafruit_VS1053_FilePlayer & mp) {
        if (mp.playingMusic)
        {
            mp.stopPlaying();
            return true;
        }
        return true;
    }

Untested, because I don't have the hardware, but that should work better.

The Adafruit_VS1053_FilePlayer object is passed **by reference** to the function, which avoids another copy being made. We are using the original one at global scope, so we don't keep creating and discarding copies. In fact, since we are using the global one you could avoid passing it to the function at all.


sender: user

message:
Proper way to run functions in loop

I am having a problem getting my functions to run properly from the loop.

I am building a model railroad crossing gate and need to run the 4 processes once the sensor signals the train entering the crossing zone. For right now I need to learn how to "function" in C++ running in loop, as I'm a C# ASP.Net guy.

My thought process was in loop to

 - Check entry sensor, this is all the loop should ever do UNTIL its tripped
 - Once tripped, run the 4 processes functions (close the gates, turn on the sound, turn on the flashers, power down the road that crosses the tracks)
 - After the entry sensor is tripped and the processes run (the sound and flashers should operate continuously until the exit sensor is cleared) the exit sensor must be monitored, and once its tripped, its monitored until it goes static again indicating the train has cleared. Then the 4 process are run to shut down the flashers, shut the sound, power up the road and raise the gates.

Right now I'm just trying to get the sound functioning properly. Right now, as the code stands, it plays for a split second then stops. I need that file playing until I call the function to stop it.

Here is the code so far. I've removed the includes and defines for brevity.

    // These are the pins used for the music maker shield
    #define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
    #define SHIELD_CS     7      // VS1053 chip select pin (output)
    #define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

    // These are common pins between breakout and shield
    #define CARDCS 4     // Card chip select pin
    // DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
    #define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

    // create shield-example object
    Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

    //global variables required
    boolean crossingSignalInOperation = false;
    boolean signalEntrySensor = false;
    boolean signalExitSensor = false;
    boolean debugMode = false;

    boolean checkEntrySensor() {
     //check entry sensor, if tripped return true otherwise false
     /*if () return true;
     return false;*/
     return true;  //hardcoded for testing
    }

    void setup() {
     // put your setup code here, to run once:
     Serial.begin(9600);
     debugMode = true;   //set this to false once code is fully operational
     //initialise music maker shield
      if (!musicPlayer.begin()) {
       if (debugMode)
       {
        Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
       }

      while (1);
     }
     // 1st parameter is left, second parameter is right
     musicPlayer.setVolume(20, 20);
     if (debugMode)
     {
      Serial.println(F("VS1053 found"));
     }

     // initialise the SD card
     SD.begin(CARDCS);

     //ensure our global booleans all start false
     crossingSignalInOperation = false;

    }

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

     signalEntrySensor = checkEntrySensor();
     if (signalEntrySensor == true) {  //only want to catch the FIRST time it senses
      if (crossingSignalInOperation == false)
      {
       //crossing signal is inactive, activate it
       // turn the sound on and return the music player object
       Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"trainxng.mp3");

       while (mp.playingMusic) {
        // file is now playing in the 'background' so now's a good time
        // to do something else
        if (!crossingSignalInOperation)
        {
         crossingSignalInOperation = true;
         //run the other three processes
         //offRoadPower();
         //lowerSignalArms();
         //startSignalFlashers();

        }
       }
      }
     }
     }

Here are the functions;

    Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
     // Play the train crossing sound file
     if (debugMode)
     {
      Serial.println(F("Playing track - "));
      Serial.print(fileName);
     }
     //all sound files are on the micro sd card on the music player shield
     if (!mp.startPlayingFile(fileName)) {
      Serial.println(F("Could not open file "));
      Serial.print(fileName);
      while (1);
     }
     return mp;
    }
    boolean offSignalSound(Adafruit_VS1053_FilePlayer mp) {
      if (mp.playingMusic)
     {
      mp.stopPlaying();
      return true;
     }
     return true;
    }

Any assistance would be appreciated.

Update:

New version using the state machine methodology suggested by JRobert and Edgar
Any comments on structure?

    // include SPI, MP3 and SD libraries
    #include <SPI.h>
    #include <Adafruit_VS1053.h>
    #include <SD.h>
    // include AccelStepper libraries
    #include <MultiStepper.h>
    #include <AccelStepper.h>
    using namespace std;
    /*-----( Declare Enums & Constants )-----*/
    // Arduino Digital I/O pin numbers for MEGA
    //note: digital pins 30-45
    //MEGA is a MUST for this project
    enum {
     Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
     Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
     Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
    };

    enum { RELAY_OFF = HIGH, RELAY_ON = LOW };

    enum {
     CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
     CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
     CROSSINGZONE_EXITING  // train detected by the exit sensor, when sensor clears state = CLEAR
    };

     enum {
      EXITSENSOR_CLEAR, // no train has passed the crossing gate exit sensor
      EXITSENSOR_ENTERED, // train detected by the exit sensor
      EXITSENSOR_WAITINGTOCLEAR // train passed by the exit sensor, when sensor clears state = CLEAR

     };

    byte state = CROSSINGZONE_CLEAR;
     //*-----( Declare Variables )-----*/
    // hardware is an optocoupler 16 channel 12V relay
    const byte relays[] = { Relay1,Relay2,Relay3,Relay4,
    Relay5,Relay6,Relay7,Relay8,
    Relay9,Relay10,Relay11,Relay12,
    Relay13,Relay14,Relay15,Relay16 };
    enum { maxRelayCount = sizeof relays / sizeof relays[0] };

    byte entrySensorPin = 26;
    byte exitSensorPin = 28;
    const char* soundFile = "trainxng.mp3";
    boolean debugMode = true;
    boolean exitSensorTripped = false;

    // These are the pins used for the music maker shield
    #define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
    #define SHIELD_CS     7      // VS1053 chip select pin (output)
    #define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
    // These are common pins between breakout and shield
    #define CARDCS 4     // Card chip select pin
    // DREQ should be an Int pin, see  http://arduino.cc/en/Reference/attachInterrupt
    #define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

    AccelStepper gateMotor1Left(AccelStepper::DRIVER, 4, 3);  // 1=Stepper driver option, 4=Step pulse pin, 3=Direction
    AccelStepper gateMotor1Right(AccelStepper::DRIVER, 6, 5);  // 1=Stepper driver option, 6=Step pulse pin, 5=Direction
    AccelStepper gateMotor2Left(AccelStepper::DRIVER, 8, 7);  // 1=Stepper driver option, 8=Step pulse pin, 7=Direction
    AccelStepper gateMotor2Right(AccelStepper::DRIVER, 10, 9);  // 1=Stepper driver option, 10=Step pulse pin, 9=Direction
    Adafruit_VS1053_FilePlayer musicPlayer =
     Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

    class CrossingGate {
      public:
     // hmm voids or booleans?
     boolean GateFlashersOn(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_ON);
      //need a check here to ensure its set LOW which is inactive for these relays
      return true;
     }
     boolean GateFlashersOff(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_OFF);
      //need a check here to ensure its set HIGH which is inactive for these relays
      return true;
     }
     boolean GateArmFlashersOn(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_ON);
      //need a check here to ensure its set LOW which is inactive for these relays
      return true;
      }
      boolean GateArmFlashersOff(byte relayNumber) {
       digitalWrite(relayNumber, RELAY_OFF);
      //need a check here to ensure its set HIGH which is inactive for these relays
      return true;
     }
     boolean GatesUp(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_ON);
      //need a check here to ensure its set LOW which is inactive for these relays
      return true;
     }
     boolean GatesDown(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_OFF);
      //need a check here to ensure its set HIGH which is inactive for these relays
      return true;
     }

    };

     class CrossingGateRoad {
       public:
        void PowerOn(byte relayNumber) {
         digitalWrite(relayNumber, RELAY_ON);

        }
        void PowerOff(byte relayNumber) {
         digitalWrite(relayNumber, RELAY_OFF);

        }
    };
    //  Sensor methods
    int CheckEntrySensor(byte esp) {
     if (digitalRead(esp) == HIGH)
     {
       state = CROSSINGZONE_CLEAR;
       return CROSSINGZONE_CLEAR;
     }
     else {
      state = CROSSINGZONE_OCCUPIED;
      return CROSSINGZONE_OCCUPIED;
     }
      return -1;
    }
    int CheckExitSensor(byte xsp) {
     if (digitalRead(xsp) == HIGH && state == CROSSINGZONE_OCCUPIED)
     {
      state = CROSSINGZONE_OCCUPIED;
      return CROSSINGZONE_OCCUPIED;
     }
     else if(digitalRead(xsp) == LOW && state == CROSSINGZONE_OCCUPIED)
        {
      state = CROSSINGZONE_CLEAR;
      return CROSSINGZONE_OCCUPIED;
     }
     return -1;
    }

    boolean CrossingBellsOn(Adafruit_VS1053_FilePlayer & mp, const char* soundFile) {
     if (!mp.startPlayingFile(soundFile)) {
      Serial.println("Could not open file trainxng.mp3 using the passed in object");
      while (1);
     }
     return true;
    }
    boolean CrossingBellsOff(Adafruit_VS1053_FilePlayer & mp) {
     if (mp.playingMusic) {
      mp.stopPlaying();
       return true;
     }
     if (mp.stopped())
     {
      return true;
     }
     return false;
    }

    CrossingGate xGate1Left;
    CrossingGate xGate1Right;
    CrossingGate xGate2Left;
    CrossingGate xGate2Right;

    CrossingGateRoad xGateRoad;

    void setup() {
     Serial.begin(9600);
     // Set max speed. Steps per second
     gateMotor1Left.setMaxSpeed(500);
     gateMotor2Left.setMaxSpeed(500);
     gateMotor1Right.setMaxSpeed(500);
     gateMotor2Right.setMaxSpeed(500);
     // set motor acceleration
     gateMotor1Left.setAcceleration(35);
     gateMotor2Left.setAcceleration(35);
     gateMotor1Right.setAcceleration(35);
     gateMotor2Right.setAcceleration(35);
     // set motor speeds
     gateMotor1Left.setSpeed(20);
     gateMotor2Left.setSpeed(20);
     gateMotor1Right.setSpeed(20);
     gateMotor2Right.setSpeed(20);

     Serial.println("Adafruit VS1053 Library Test");
     // initialise the music player
     if (!musicPlayer.begin()) { // initialise the music player
       Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
      while (1);
     }
     Serial.println(F("VS1053 found"));
     //musicPlayer.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working
     // check the card reader
     if (!SD.begin(CARDCS)) {
      Serial.println(F("SD failed, or not present"));
      while (1);
     }
     Serial.println("SD OK!");
     // Set volume for left, right channels. lower numbers == louder volume!
     musicPlayer.setVolume(20, 20);

     // This option uses a pin interrupt. But DREQ must be on an
     //  interrupt pin. For Uno/Duemilanove/Diecimilla that's Digital #2 or #3
      // See http://arduino.cc/en/Reference/attachInterrupt for other pins
     // * This is the preferred method
     if (!musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT))
      Serial.println(F("DREQ pin is not an interrupt pin"));

    }
    void loop() {

     switch (state) {
         case CROSSINGZONE_CLEAR:
        // Check entry sensor. If tripped, turn on the sound.
       if (CheckEntrySensor(entrySensorPin) == 1) {
       // first go around i'll try to tun all these here otherwise
       // I will break out to more states
       //these happen instantly
       xGateRoad.PowerOff(relays[0]);
       xGate1Left.GateArmFlashersOn(relays[1]);
       xGate1Right.GateArmFlashersOn(relays[2]);
       xGate2Left.GateArmFlashersOn(relays[3]);
       xGate2Right.GateArmFlashersOn(relays[4]);
       xGate1Left.GateFlashersOn(relays[5]);
       xGate1Right.GateFlashersOn(relays[6]);
       xGate2Left.GateFlashersOn(relays[7]);
       xGate2Right.GateFlashersOn(relays[8]);
       //these take some time
       xGate1Left.GatesDown(relays[9]);
       xGate1Right.GatesDown(relays[10]);
       xGate2Left.GatesDown(relays[11]);
       xGate2Right.GatesDown(relays[12]);
       //this is the last process, if it completes change state
       if (CrossingBellsOn(musicPlayer, soundFile)) {
        state = CROSSINGZONE_OCCUPIED;
       }
      }
      else {
       state = CROSSINGZONE_CLEAR;
      }
      break;
     case CROSSINGZONE_OCCUPIED:
      // Once zone is occupied, monitor the exit sensor
      if (CheckExitSensor(exitSensorPin) == 0) { // Exit sensor not tripped yet
       state = CROSSINGZONE_OCCUPIED;
      }
      else {
       exitSensorTripped = true;
      }
      if (exitSensorTripped)
      {
        // need to code here to wait until Exit Sensor has 1500 milliseconds where its clear
       // to indicate that the last car of train has passed it
       // if above set exitSensorTripped back to false and state to EXITING
       state = CROSSINGZONE_EXITING;
      }
      break;
     case CROSSINGZONE_EXITING:
      // Check if the train has cleared, then shut the sound.
      if (CheckExitSensor(exitSensorPin) == 1) {
       // first go around i'll try to tun all these here otherwise
       // I will break out to more states
       //these happen instantly
       xGateRoad.PowerOn(relays[0]);
       xGate1Left.GateArmFlashersOff(relays[1]);
       xGate1Right.GateArmFlashersOff(relays[2]);
       xGate2Left.GateArmFlashersOff(relays[3]);
       xGate2Right.GateArmFlashersOff(relays[4]);
       xGate1Left.GateArmFlashersOff(relays[5]);
       xGate1Right.GateArmFlashersOff(relays[6]);
       xGate2Left.GateArmFlashersOff(relays[7]);
       xGate2Right.GateArmFlashersOff(relays[8]);
       //these take some time
       xGate1Left.GatesUp(relays[9]);
       xGate1Right.GatesUp(relays[10]);
       xGate2Left.GatesUp(relays[11]);
       xGate2Right.GatesUp(relays[12]);
       //this is the last process, if it completes change state
       if (CrossingBellsOff(musicPlayer)) {
        state = CROSSINGZONE_CLEAR;
       }
      }
      break;
     }
    }

sender: assistant

body:
Elaborating on JRobert's answer, which I think is definitively the way
to go. Here is a typical way of writing a state machine with only three
states:

1. No train in the area. You are monitoring the entry sensor.
2. You have detected the train on the entry sensor. You started playing
   the sound. You are monitoring the exit sensor.
3. You have detected the train on the exit sensor. You are still
   monitoring the same sensor in order to know when the train clears the
   area.

Notice that the _actions_ you perform (starting and stopping the sound
for instance) are not associated with a particular state but with a
_transition_ between states: you start the sound on the 1 → 2
transition and stop it on 3 → 1.

Here is the code for `loop()`:

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

    void loop() {
        static enum {
            NO_TRAIN,        // no train in the area
            TRAIN_ENTERED,   // train seen by the entry sensor
            TRAIN_EXITING    // train seen by the exit sensor
        } state = NO_TRAIN;  // initial state

        switch (state) {
            case NO_TRAIN:
                // Check entry sensor. If tripped, turn on the sound.
                if (checkEntrySensor()) {
                    musicPlayer.startPlayingFile("trainxng.mp3");
                    flashers.turnOn();
                    gates.close();
                    road.powerDown();
                    state = TRAIN_ENTERED;
                }
                break;
            case TRAIN_ENTERED:
                // The exit sensor must be monitored.
                if (checkExitSensor()) {
                    state = TRAIN_EXITING;
                }
                break;
            case TRAIN_EXITING:
                // Check if the train has cleared, then shut the sound.
                if (!checkExitSensor()) {
                    musicPlayer.stopPlaying();
                    flashers.turnOff();
                    gates.open();
                    road.powerUp();
                    state = NO_TRAIN;
                }
                break;
        }
    }

This may be a bit oversimplified: if an action need some time, you may
have to create an extra state for it. For example, in order to avoid
blocking the program while the barrier goes down, you can split the
transition `NO_TRAIN → TRAIN_ENTERED` in two:

    NO_TRAIN → LOWERING_BARRIER → TRAIN_ENTERED

and the action “lower the barrier” is itself split into “start lowering
the barrier” (on the first transition) and “stop lowering the barrier”
(on the second transition).


message:
User callback functions

I want to write a class that allows the user to attach his own function to a member function that listens for messages coming from a wireless module, so that the user's function can be called depending on the message.

I am thinking about using function pointers but I don't know how it will work since I don't know the user's function parameters, return type and number of functions that will be added.

    //sketch.ino

    <unknown> (*funcPtr)(<unknown>)[<unknown>];

    void receive() {
      message.type = 'o';
      if (message.available()) {
        message.receive();
      }
      switch (message.type) {
        case 'p': {
          Serial.println(p);
          break;
        }
        case 'f': {
          funcPtr[message.funcID](message.parameter1, message.parameter2);
          break;
        }
        default: break;
    }

    void userFunction1() {
      Serial.println("User function 1");
    }

    int userFunction2(int x) {
      return x * 2;
    }

    funcPtr[0] = &userFunction1;
    funcPtr[1] = &userFunction2;

    void setup() {}

    void loop() {
      receive();
    }

Is this kind of thing possible?

body:
You can't call **arbitrary** functions (with random return types, and any number of arguments) but you can specify a callback function that takes a certain number of specific arguments, and returns a certain thing (or nothing).

See <http://www.gammon.com.au/callbacks>

Example code:

    typedef void (*GeneralMessageFunction) ();

    void sayHello ()
      {
      Serial.println ("Hello!");
      }  // end of sayHello

    void sayGoodbye ()
      {
      Serial.println ("Goodbye!");
      }  // end of sayGoodbye

    void checkPin (const int pin, GeneralMessageFunction response); // prototype

    void checkPin (const int pin, GeneralMessageFunction response)
      {
      if (digitalRead (pin) == LOW)
         {
         response ();  // call the callback function
         delay (500);  // debounce
         }
      }  // end of checkPin

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      pinMode (8, INPUT_PULLUP);
      pinMode (9, INPUT_PULLUP);
      }  // end of setup

    void loop ()
      {
      checkPin (8, sayHello);
      checkPin (9, sayGoodbye);
      }  // end of loop

---

>  I don't know how it will work since I don't know the user's function parameters, return type and number of functions that will be added.

You will need to tell the user what sort of function to write. For example, a function that takes a string (ie. the message) and returns a boolean (whether it was handled or not).


body:
> I don't know the user's function parameters,

A common way for dealing with this issue is to pass a generic pointer to
arbitrary data. See below.

> return type

It makes little sense to allow for arbitrary return types, as your
library would have no way of knowing what to do with the returned value.

> and number of functions that will be added.

Either you allocate the callback array statically with a fixed size, or
you use dynamic allocation. In the first case, the array size could be
decided by the user if it is a template parameter. In the second case,
you risk memory fragmentation unless all the callbacks are registered
once and for all at program startup, which is a common scenario anyway.

------------------------------------------------------------------------

## About the generic pointer technique

This is a very common way of defining callbacks in C: a callback
contains both a function and a `void *` pointer to arbitrary data, which
will be given as a parameter to the function. It is up to the user to
decide if and how he will use this pointer: he could completely ignore
it, like he could make it point to the root of a complex data tree.

Here is a simple example:

    // A callback contains both a function and a pointer to arbitrary data
    // that will be passed as argument to the function.
    struct Callback {
        Callback(void (*f)(void *) = 0, void *d = 0)
            : function(f), data(d) {}
        void (*function)(void *);
        void *data;
    };

    Callback callbacks[3];

    // This callback expects an int.
    void print_int(void *data)
    {
        int parameter = * (int *) data;
        Serial.println(parameter);
    }

    // This one expects a C string.
    void print_string(void *data)
    {
        char * parameter = (char *) data;
        Serial.println(parameter);
    }

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

        // Register callbacks.
        static int seventeen = 17;
        static int forty_two = 42;
        static char hello[] = "Hello, World!";
        callbacks[0] = Callback(print_int, &seventeen);
        callbacks[1] = Callback(print_int, &forty_two);
        callbacks[2] = Callback(print_string, hello);
    }

    void loop()
    {
        // Test all the callbacks.
        for (size_t i = 0; i < 3; i++)
            callbacks[i].function(callbacks[i].data);
        delay(500);
    }

Notice that the two callback functions take different types of
parameters, only disguised into the same generic pointer. Notice also
that `print_int` is used in two different callbacks with different data.
In this example, the data does not change, but this need not be the
case: both the callbacks and the rest of the user code could change the
data pointed to by the generic pointers. Again, it is up to the user to
decide how he will use this facility to communicate between his
callbacks and the rest of his code.


message:
Trying to send data to the server and AT+CIPSEND not working correctly

Sending data to the server(thingspeak.com/184.106.153.14) with AT commands on serial monitor works fine but whenever i upload the sketch ,the following always return false `if(Serial.find( ">" ) )`. I am not sure if `AT+CIPSEND` is not working correctly or what. I am using Arduino with ESP8266. Any help will be appreciated.Thanks you in advance. Here is my code.

      #include <SoftwareSerial.h>
      SoftwareSerial softSerial(2, 3); // RX, TX

      #define SSID "myssid"
      #define PASS "Mypass"
      #define IP "184.106.153.149" // ThingSpeak

      void setup()
      {
       uint32_t baud = 9600;
       Serial.begin(baud);
       softSerial.begin(baud);

       connectWiFi();
       }

       void loop()
       {
        updateTS();
        }

        void updateTS()
        {
        String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
        cmd += IP;
        cmd += "\",80";
        sendDebug(cmd);
        delay(2000);

        String url = "GET /update?key=P55Z0BDASNQBFQKT&field1=15&field2=25\r\n\r\n"; //hard code value 15 and 25
        String stringLength="AT+CIPSEND=";
        stringLength +=String(url.length( ));
        Serial.println(stringLength);
        //delay(10000); I even tried to delay for few seconds

       //Here is where it fails,it jumps to closing the connection
       if(Serial.find( ">" ) )
        {
         softSerial.print(">");
         softSerial.print(cmds);
         Serial.print(cmds);
        }
        else
        {
         sendDebug( "AT+CIPCLOSE" );//close TCP connection
        }

        }

       void sendDebug(String cmd)
        {
          softSerial.print("SEND: ");
          softSerial.println(cmd);
          Serial.println(cmd);
         }

         boolean connectWiFi()
        {
          Serial.println("AT+CWMODE=1");
          delay(2000);
          String cmd="AT+CWJAP=\""; // Join accespoint
          cmd+=SSID;
          cmd+="\",\"";
          cmd+=PASS;
          cmd+="\"";
          sendDebug(cmd);
          delay(5000);
          if(Serial.find("OK"))
          {
           softSerial.println("RECEIVED: OK");
           return true;
          }
          else
          {
           softSerial.println("RECEIVED: Error");
           return false;
           }
         }

body:
Your code looks like you connected the ESP to the hardware serial port, but your comment says otherwise so:

Your sketch isnt working because you're writing to the wrong serial port half the time, and even when you do use the right serial port (`softSerial`) you're sending garbage along with it.

`Serial.println(stringLength);` and `Serial.find("OK")` should be `softSerial.println(stringLength);` and `softSerial.find("OK")`.

`Serial.find( ">" )` should be `softSerial.find( ">" )`. You should look for '>' in the buffer between the **Arduino and the ESP8266** and not the one between the Arduino and the PC.

`softSerial.print(">");`, `softSerial.println("RECEIVED: OK");` and similar statements should not be there at all. They are not commands or arguments to a command so why are you printing them to the ESP? Whenever you write to `softSerial`, make sure its a **command**. Dont send your debug messages to `softSerial`; use `Serial` instead.

There's no variable called `cmds` and yet you're printing it to the serial port. Assuming this code compiled, its probably a typo in your question?

Finally, your code structure is unreliable at best, what with all the delays in it and not a single `Serial.available()` or `softSerial.available()`, not to mention the abundant usage of Arduino Strings. I suggest you first learn how to read from a serial port and build C strings from the results and **then** re-design your code again. [Majenko's blog][1] is as good a tutorial as any. Or you could download a library like [this one][2] that provides an easy API to the ESP8266, shielding you from the mess of AT commands, while providing you with example sketches that already do what you want. Of course, you could choose to go through their library (.cpp and .h files are the place to be) and figure out how *they* used AT commands with the ESP and *then* write your own sketch, library or whatever. Good luck.

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/
  [2]: https://github.com/itead/ITEADLIB_Arduino_WeeESP8266


message:
'Non-Deterministic' memory usage on Arduino

I had a problem with a memory leak in my sketch and cornered it with `MemoryFree.h`. This works great and I was able to fix my leak.

My sketch is not really static, but My var sizes are. I observed, that the free memory on the arduino reaches a different values and stays there.

For Example

 1. Run 1: 1655 Bytes Free
 2. Run 2: 1659 Bytes Free
 3. Run 3: 1654 Bytes Free

For every run, I get a different, but over a short time, fixed memory usage. Is this normal?

P.S: The serial input to the script just repeats forever with the exact same data.

body:
You haven't posted any code, so any answer is guesswork. However ... if your code makes decisions based on external events (eg. readings from sensors) then it may allocate memory differently, and in a different order, each time.

Sometimes memory allocation leaves gaps (known as "heap fragmentation"). Small differences in your results probably show slightly different sized gaps, due to the allocation order.


message:
PFC8574 4x4 keypad: correct wiring?

I bought a few PFC8574 and 4x4 keypads for a small project. I'm unclear on the correct wiring of the keypad to the PFC8574.

On the [Arduino Playground's site][1], there are pull-up resistors for each column, but on a few other sites (like [this one][2] that I can't read, but I understand a schematic and there's a third example too, but I don't have the reputation to post it), the wiring does straight into the IC.

Does it depend on the library that's being used?  Or what am I missing?

Thanks!

  [1]: http://playground.arduino.cc/Main/I2CPortExpanderAndKeypads
  [2]: http://majsterkowo.pl/klawiatura-numeryczna-pod-i2c/

body:
Ok look at this image:
[![enter image description here][1]][1]

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

I'm not sure how your keypad is layed out but if you use a probe pin to test your connections via a multimeter, you can mark which ones correspond to the image.

I am ASSUMING you are going to use the code from arduino playground.

This is the format:

Pins of keypad (**IN THE IMAGE**) - Pins of PFC8547

Here are the pin connections:

1 - nothing

2 - 9

3 - 4

4 - 6

5 - 7

6 - 10

7 - 11

8 - 5

Also include the pull-up resistors.
Your ABCD keys will be ignored

(This is like wiring a bomb...)


message:
Ethernet shield or Wifi sheild - Arduino?

To control some LEDs through internet using Arduino UNO, which type of connection  is better ? Ethernet or Wifi? (Later, I may connect some relays instead of LEDs, and control (turn on and off) some devices using this setup).
The only difference I know is the wired and wireless connectivity.
Is there any other difference?

body:
If you are beginner with Arduino its better to start with [Ethernet Shield][1]. Its much more easy to connect with Arduino.

WiFi Module - [ESP8266][2] required some more knowledge, that you will learn in future.

The bought products are cheap, so you can start with Ethernet and after that to switch to ESP.

  [1]: https://www.arduino.cc/en/Guide/ArduinoEthernetShield
  [2]: http://www.esp8266.com/


message:
Using Processing to send data to Arduino

import processing.serial.*;
    import java.io.*;
    Serial myPort;
    int mySwitch;
    String transmitter[] = new String[1280000]; //initialize array

    void setup(){
             mySwitch=1;
             //Open the serial port for communication with the Arduino
             //Make sure the COM port is correct
             myPort = new Serial(this, "COM6", 9600);
             myPort.bufferUntil('\n');
    }

    void draw() {
            if(mySwitch == 1)
            {
               readData("input.txt");
               int index = 0;
               while(index < 128000)
               {
                 myPort.write(transmitter[index++]);
                 if(index8 == 0)
                   delay(100);
               }
            }

             mySwitch = 0;
    }

    void readData(String myFileName){

             File file=new File(myFileName);
             BufferedReader br=null;

             try{
               br=new BufferedReader(new FileReader(file));

               String transmit=null;
               int i = 0;
               /* keep reading each line until you get to the end of the file */
                    while((transmit = br.readLine()) != null)
                       transmitter[i++] = transmit;

             }catch(FileNotFoundException e){ e.printStackTrace(); }

             catch(IOException e){ e.printStackTrace(); }

             finally{
                     try {
                       if (br != null) br.close();
                     }
                     catch (IOException e) { e.printStackTrace(); }
             }
    }
In the above code, I have an String array and I'm reading lines from a file and saving them as strings. How would I save them as byte/char inside an array of byte/char?

Basically, I have a file of integers on each line, each integer in the range [0, 255]. And I want to read this integer and send it to the Arduino. The Arduino serial.read() function reads a byte at a time. This is the issue I am trying to solve.

body:
I believe I have actually found a very efficient solution to this problem by re-writing the code the following way by using the "Scanner" class and not the "BufferedReader" class. Any input on making this more efficient is welcome!

    import processing.serial.*;
 import java.io.*;
 import java.util.*;
 Serial myPort;
 int mySwitch;
 Scanner file;
 byte transmitter[] = new byte[1280000]; //initialize array

 void setup(){
     mySwitch=1;
     //Open the serial port for communication with the Arduino
     //Make sure the COM port is correct
     myPort = new Serial(this, "COM6", 9600);
     myPort.bufferUntil('\n');
 }

 void draw() {
     if(mySwitch == 1)
     {
         readData("input.txt");
         int index = 0;
         while(index < 128000)
         {
             myPort.write(transmitter[index++]);
             if(index8 == 0)
                 delay(100);
         }
     }

     mySwitch = 0;
 }

 void readData(String myFileName){
     try{
       file = new Scanner(new File(myFileName));
     }
     catch(Exception e){System.out.println("NOT FOUND!");}

     int i = 0;
     while(file.hasNextByte())
       transmitter[i++] = file.nextByte();

     file.close();
 }


message:
Regarding the output voltage and current in arduino

This is basically an off-shoot from [https://arduino.stackexchange.com/questions/20569/unexpected-output-pin-behavior-was-relay-on-off-doesnt-loop][1]. It's the same schematics and so on, however, I'm now wondering what the output voltage and current is.

I've a 9V battery and the MOSFET transistor from the arduino starterpack (doesn't say the specs) connected to the 5V pin on the board. I need the following output current/voltage for it to activate a solenoid:

 - 6V: 160 mA
 - 7V: 190 mA
 - 8V: 220 mA
 - 9V 240 mA
 - 10V :270 mA
 - 11V :300 mA
 - 12V :320 mA

and I'm just not sure how to calculate it since I'm not sure about the output from the transistor and all the way to the solenoid.

The solenoid: http://www.electrokit.com/en/plastic-water-solenoid-valve-1-2-12v.51108

[![It should be solenoid instead of relay in the schematics][2]][2]

  [1]: https://arduino.stackexchange.com/questions/20569/unexpected-output-pin-behavior-was-relay-on-off-doesnt-loop
  [2]: https://i.stack.imgur.com/ElqV9.png

body:
You don't need to "calculate" anything with a MOSFET.  You will be using it in the *saturation* zone. That means it is fully turned on and will allow through the current you need.

However, the gate of a MOSFET looks, to all intents and purposes, like a small capacitor. That means there will be a certain amount of *inrush* current to the gate when you turn it on. To limit that inrush current you need a small resistor (say 100-220Ω) on the gate.

When using a BJT, though, you need to ensure that you allow enough current through the base to allow enough current through the collector.  Divide the current you need through the collector by the *Hfe* (typically 100 for a small signal transistor) and that is the *minimum* current you need to allow through the base. Subtract a silicon junction voltage (0.6V) from the voltage of the IO pin (5V). Divide it by your base current calculated above, and that is the *maximum* resistor you can use on the base.

And also your transistor symbol in your schematic is backwards.


message:
Can I reassign my Arduino Uno COM Port?

The Arduino SW, under Tools, identifies my Uno as COM Port 3. However, COM Port 3 on my computer is in use by a chip set. My computer assigned COM Port 4 to my Arduino Uno.

Can I reassign my Uno to COM Port 4?

Edit: This question also applies to people who don't have administrative privileges. They do not have privileges to change the port via Windows Device Manager.

body: If the Arduino IDE identified your Uno as COM Port 3, your computer most likely has already assigned COM Port 3 to your Uno. You can double check the port assignment in Device manager > Ports.


body:
You can change your COM Port number for a device by following these instructions:

 http://plugable.com/2011/07/04/how-to-change-the-com-port-for-a-usb-serial-adapter-on-windows-7


message:
How can I control neopixels attached to a Digispark?

I want to use a string of Neopixels attached to a Digispark hanging off of a RasPi3 as indicators for various situations.  For example: a motor (connected to a driver hat on the I2C bus of the RasPi) turns on or reverses direction.  Can I use Firmata, or is there something like it for the Digispark that I can use with Python?

body:
You need a dedicated microcontroller since you need very precise timing for controlling the neopixels. It works well on an ATTiny85, we are using Adafruit Trinket boards to control Neopixels and work well. So far up to 12 pixels :)

You can download a Trinket Neopixel library, which is modded for an internal osc ATTiny85 from Adafruit.

Then your Raspi can talk to the microcontroller. It is a little problematic, though, since the software serial port handling consumes too much memory on ATTiny, and the ATTiny will ignore all serial input while refreshing the neopixels. Therefore you may get it easier by using an Arduino UNO, or Leonardo or Micro which is powerful enough for many pixels, and have a built-in hardware serial port.

As a matter of fact, you can talk to these Arduino boards as if it would be a serial port, so just plug in a Leonardo over USB and you'll get a new serial port in Rpi to talk to.


body: A circuit can be made using two 74HC121s and an OR gate that would be connected to the SPI peripheral in the microcontroller. The timing would be accomplished by the multi-vibrators while each byte would be output through the serial port.


message:
Streaming audio from PC to Arduino over WiFi

Say I wanted to, *purely hypothetically*, set up a pirate radio station by connecting an Arduino to a WiFi network away from home, streaming music to the Arduino, decoding it, and broadcasting it with an FM transmitter.

Given an **Arduino (Genuino) Uno**, a **Sparkfun ESP8266 Thing Dev** breakout board for WiFi connectivity, and an **Adafruit Si4713 Stereo FM Transmitter** breakout board, how would I go about the actual streaming of music (in MP3 or WAV format) from a (Windows) computer to the Arduino over WiFi? Would an Arduino Uno be powerful enough for this? Which components would I need to decode the audio?

body:
Well, a sort of... You can stream 64kbps MP3, get it via wifi from esp8266. Then for all the rest, forget the Arduino.

You need a dedicated MP3 decoder chip (many out there, sta013 was one of the oldest beasts) which can take the digital mp3 stream and convert it to analog output.

You can feed the line level analog output to the FM Transmitter, and then you're golden.

Note that you shall develop some application on the PC to actually stream out the MP3 - an off the shelf solution such as a Shoutcast server may not work, as the usual web-radio stations inject station data and currently played track metadata into the mp3 stream what you have to remove from the MP3 decoder chip.

Since the actual wifi bandwidth with ESP is limited (as well as the processing power of the Arduino), you may switch to a more efficient compression format. For example, a 64kbps WMA sounds far better than a 64kbps MP3, and at 64kbps AAC is superior to any of the other formats. Ensure that your decoder chip can work well with a modern codec comperssion format.


message:
Critical sections in Arduino, interrupt consuming data

We all *know* the interrupts, but how do they really work?

**The problem:**

In my sketch an interrupt method (invoked when pin goes high) is consuming data from a buffer and the main `loop()` is filling the buffer at random speeds (from Internet - I'm using ESP8266, not the Arduino). Although I think there shouldn't be any *threading* problems with this buffer - I might be wrong - the program hangs up after random number of seconds (about half a minute average - and then the built-in watchdog resets it after few seconds). When I detached the interrupt method and merged it into the main `loop()` code, the problem disappeared (but I can't leave it like that). So it's probably either that I'm doing something illegal in the interrupt method (maybe it's just taking too long - how much time can an interrupt method take?) - or the second possibility - it **is** a threading problem.

**The questions:**

The main question is: how to correctly synchronize the interrupt method? How to create a critical section if the interrupt method cannot wait (for a semaphore) and if I leave it, it won't be invoked again because the pin is already high? And the detailed questions:

 1. How to create a *thread-safe* variable (a bool flag), so that interrupt method can skip the critical section if the main loop has entered it? (I understand the interrupt method is "safe" - it won't be interrupted - but how to secure the regular code?)
 2. If I detach an interrupt method that is triggered when a pin goes high when it is low (for just a few fast instructions), the pin gets high in that time, and then I'll re-attach the method to this pin again, will it be invoked? The same question for `noInterrupts();` How to make sure it **will** be invoked, if I can't check the pin and invoke (or not) the method manually in an atomic transaction with re-attaching the method?
 3. If I detach this method (in main loop), is it possible that it will be invoked before the control is back from the `detachInterrupt()` method? (because the pin got high from external device in this very moment) And the same question for `noInterrupts();`
 4. I've read that `noInterrupts();` causes some things, like reading incoming serial data, to be skipped. Can this method be even used if I don't want that? Or can I have guaranteed that it won't happen if the method is fast enough? (if so, please define the "fast enough"!)

So, is there a common template for creating a critical section between an interrupt method and the regular code? Or at least synchronizing a variable access? And if not, how to make sure the detached/blocked pin method will be invoked after re-attaching/re-enabling it?

**The common buffer code:**

(if you want to check whether this can cause any "threading" problems)

    class Buffer
    {
      protected:
        byte *buf;
        int len, readpos, writepos;
        bool wasFull, wasEmpty;
        long ratioSum, ratioCount;

      public:
        Buffer(int length)
        {
          len = length;
          buf = new byte[len];
          readpos = writepos = 0;
        }

        bool isFull()
        {
          bool full = writepos - readpos >= len;
          wasFull &= full;
          return full;
        }

        bool isEmpty()
        {
          bool empty = readpos >= writepos;
          wasEmpty &= empty;
          return empty;
        }

        void write(byte b)
        {
          if (isFull()) { if (!wasFull) { wasFull = true; Serial.println("Error: Buffer overflow!"); } return; }
          int pos = (writepos++) % len;
          buf[pos] = b;
          if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
        }

        byte read()
        {
          if (isEmpty()) { if (!wasEmpty) { wasEmpty = true; Serial.println("Error: Buffer underflow!"); } return 0; }
          int pos = (readpos++) % len;
          if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
          return buf[pos];
        }

        int available()
        {
          return writepos - readpos;
        }

        void measureRatio()
        {
          ratioSum += available();
          ratioCount++;
        }

        int getRatio()
        {
          int ratio;
          if (ratioCount > 0)
            ratio = 100 * ((float)(ratioSum / ratioCount) / (float)len);
          else
            ratio = 100 * ((float)available() / (float)len);
          ratioSum = 0;
          ratioCount = 0;
          return ratio;
        }
    };

**PS:**

I have discovered that printing to Serial in the interrupt method (even without a `flush()` is causing my program to crash after max half a second. Is it just a duration of printing or is it something else? Also if you're thinking that the warning printing in my Buffer code can cause the crashes, then I assure you that they're not because I always check isEmpty() and isFull() before each read and write operation, so they just can't occur.

body:
The trick here is not to make your interrupt routine, or your main routine "thread safe" - instead you need to make the single item that is shared by the two "thread safe". That means your Buffer class.

You need to go through that with a fine toothed comb and work out which bits could possibly be accessed by the two contexts at once and protect them.

The bits that jump out at me immediately are the calculations and manipulations of writepos and readpos. Accesses to those variables need to be made as atomic as possible.  One of the best ways of doing that is to massively restrict the actual access to those variables and wrap those accesses in critical sections (disable / enable interrupts). That keeps the critical sections as short as possible.

For instance, instead of directly manipulating the variables, as you enter the function you first create "cached" copies of the variables you will modify that could be modified at the same time (such as writepos being written to in the ISR):

    cli();
    int cachedWritePos = writepos;
    sei();

Then you do your manipulations and calculations on those cached variables. Finally, just before you exit the function, you write your now safely changed cached variable values back to the member variables:

    cli();
    writepos = cachedWritePos;
    sei();

The critical sections are then as brief as possible, and any heavy calculations (I count the modulus operator `%` as a heavy calculation) don't block the interrupt from firing.

Of course that is not a foolproof method and doesn't protect against two contexts changing the same variable and it getting out of step. To counter that you will have to use a mutex. There's no getting around that, other than ensuring that your program never changes the same variables from two different contexts. The only mutex you really have access to is a manually implemented [spinlock](https://en.wikipedia.org/wiki/Spinlock).

On that note, I am having some trouble following the logical flow of how your buffer works. There are bits that don't look quite right to me, such as this bit:

    if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }

According to my way of thinking both readpos and writepos have to have reached (or exceeded) the end of the buffer for them to wrap around to the start again.  That can't really happen properly in a function that is only writing, or a function that is only reading. I think you want to only be checking writepos and wrapping that in the write function, and only checking readpos and wrapping that around in the read function, not both in both functions.

As far as using Serial in an interrupt goes, the general rule is: don't do it.  I don't know about the ESP8266's serial code, but certainly on the Arduino it relies on interrupts being used to take each character from the TX buffer and transmitting it through the UART interface. If you are in an interrupt routine and your (64 byte) serial TX buffer fills up any attempts to write to that buffer (Serial.print) will block until the interrupt that sends the characters has made some room for you - and of course that interrupt will never happen while you're blocking because you are in an interrupt at the time.

On systems with multiple priority levels of interrupt (such as a PIC32) the same holds true if you are in an interrupt routine that is at a higher priority than the Serial interrupt. If you are in a lower priority one the serial interrupt can still interrupt your current interrupt routine and function correctly.


body:
**Warning**: I am not familiar with the ESP8266 hardware, and some of my
answers below may be only valid on the AVR architecture.

The simplest way to synchronize your main code with your interrupt
service routine is to define a _critical section_ in your `loop()` that
wraps access to the shared data, and to make sure this critical section
cannot be interrupted:

    noInterrupts();
    buffer.write(data);
    interrupts();

This should be fine as long as you make the critical section as short as
possible. Majenko's recommendation, to inspect the `write()` method with
“a fine toothed comb” in order to minimize the critical section, is
definitively good advice.

To understand the relevance of the “as short as possible” requirement,
think about what could happen if the interrupt triggering event (the pin
going high) happens while interrupts are disabled. If this happens
_once_, it's not a problem: the interrupt is put on hold (technically,
an _interrupt flag_ is raised), and then it's serviced as soon as
interrupts are enabled again. However, if the pin goes high _twice_
while interrupts are blocked, then, when you enable interrupts again,
the interrupt handler will be called only once. Whether this is a
problem or not I cannot say, it all depends on what job the handler is
supposed to do.

Now, to the specific sub-questions:

> How to create a thread-safe variable (a bool flag)

Chances are the boolean can be read and set atomically, so it's
inherently thread-safe. On an 8-bit CPU, like the AVR, access to a
multi-byte variable has to be protected inside a critical section. But
since you have a 32-bit CPU, I bet you have atomic access to variables
up to 32-bit wide.

> If I detach an interrupt method that is triggered when a pin goes high
> when it is low (for just a few fast instructions), the pin gets high
> in that time, and then I'll re-attach the method to this pin again,
> will it be invoked?

Hard to say without reading both the datasheet of the hardware and the
source code of `attachInterrupt()`. It may be safer to keep the handler
attached and start its code with something like
`if (doNotRunInterruptHandler) return;`.

> The same question for noInterrupts();

Yes, it will be invoked, but at most once.

> If I detach this method (in main loop), is it possible that it will be
> invoked before the control is back from the detachInterrupt() method?

Yes, the interrupt can fire while `detachInterrupt()` is checking to see
whether you gave it valid parameters.

> same question for noInterrupts();

Check the implementation. On the AVR, `noInterrupts()` is atomic.

> I've read that noInterrupts(); causes some things, like reading
> incoming serial data, to be skipped.

Nothing like this will happen if your critical section is fast enough.

> please define the "fast enough"!

It depends on how long you can afford to delay the interrupt service
routine. For example, if you are reading serial data at 115200 bps
and the UART has only a one-byte buffer, then a 86 µs critical
section can make you loose one byte.

Then, there is the risk that several interrupts of the same kind fire
during the same same critical section. As said before, the interrupt
will only be serviced once. If this is a problem, then you should not
block interrupts for longer than the minimum possible period of the
triggering event.

Also, there is always the risk that several, _unrelated_ interrupts fire
during the same critical section. Then, the one with the lowest priority
will have to wait for the critical section to finish _and then_ for the
higher priority interrupt to be serviced.


body:
**My problem with crashing is fixed! :)** I will share here what was wrong - maybe someone will have similar problem in the future.

But first...

I have marked Edgar Bonet's answer because he answered most of the difficult questions that were bothering me and for pointing me out that reading a 16-bit variable on 8-bit processor is **not atomic** (it was the most significant clue) and for helping me to understand that `noInterrupts()` is the safe and only way to synchronize with the interrupt method in my case. Thanks Edgar! But credits also go to Majenko because I wouldn't have guessed it without him. He pushed me into the right direction in our chat discussion - that I have to secure **all** the methods accessing `readpos` and `writepos`. Thanks Majenko. I agree with him that my Buffer code is ugly and it's not a good way to implement a circular buffer, but it was still logically OK - it just needed one more thing...

**The solution**

You probably know it already. The key is the non-atomic **reading** of `readpos` and `writepos`. For example: the code from `loop()` starts to read `readpos`, reads the first byte of it, then the interrupt happens, `readpos` changes there and the `loop()` continues reading the other (changed) half, which is then glued with the old (out of date) half - so - a random value. Or another one: the loop writes first byte of `writepos` (as it fills the buffer) and then interrupt fires and reads the first (changed) byte with the old (out of date) second byte. So the solution is to just wrap all access to those variables with `noInterrupts()` - and the whole code works perfect! :) Thank you guys! Not only for helping me to fix it, but for helping me to understand it.

Here is how it looks like now (non-crashing version):

    class Buffer
    {
      protected:
        byte *buf;
        const int len;
        int readpos, writepos;
        bool wasFull, wasEmpty;
        long ratioSum, ratioCount;

      public:
        Buffer(const int length)
          : len(length)
        {
          buf = new byte[len];
          readpos = writepos = 0;
        }

        bool isFull()
        {
          noInterrupts();
          bool full = writepos - readpos >= len;
          wasFull &= full;
          interrupts();
          return full;
        }

        bool isEmpty()
        {
          noInterrupts();
          bool empty = readpos >= writepos;
          wasEmpty &= empty;
          interrupts();
          return empty;
        }

        void write(byte b)
        {
          if (isFull()) return;//{ if (!wasFull) { wasFull = true; Serial.println("Error: Buffer overflow!"); } return; }
          int pos = (writepos++) % len;
          buf[pos] = b;
          if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
        }

        byte read()
        {
          if (isEmpty()) return 0;// { if (!wasEmpty) { wasEmpty = true; Serial.println("Error: Buffer underflow!"); } return 0; }
          int pos = (readpos++) % len;
          //if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
          return buf[pos];
        }

        int available()
        {
          noInterrupts();
          int result = writepos - readpos;
          interrupts();
          return result;
        }

        int free()
        {
          noInterrupts();
          int result = len - available();
          interrupts();
          return result;
        }

        void MeasureRatio()
        {
          ratioSum += available();
          ratioCount++;
        }

        int getRatio()
        {
          int ratio;
          if (ratioCount > 0)
            ratio = 100 * ((float)(ratioSum / ratioCount) / (float)len);
          else
            ratio = 100 * ((float)available() / (float)len);
          ratioSum = 0;
          ratioCount = 0;
          return ratio;
        }
    };


message:
Disable other buttons while one of buttons is pressed

I'm making a project with three buttons. What I'm trying to do is to disable other buttons (make them not respond to a click event) when one of three buttons is pressed.

For now I have this code:

        const int button1=3;
        const int button2=4;
        const int button3=5;

        int button1State=0;
        int button2State=0;
        int button3State=0;

        void setup() {
        pinMode(button1, INPUT);
        pinMode(button2, INPUT);
        pinMode(button3, INPUT);
        }

       void loop() {
       button1State=digitalRead(button1);
       button2State=digitalRead(button2);
       button3State=digitalRead(button3);

       if( button1State == HIGH){
       // do some stuff
       }

        if( button2State == HIGH){
        // do some stuff
        }

        if( button3State == HIGH){
        // do some stuff
        }

        }

Do you have any ideas how I could do it?

Thanks is advance for any suggestions!

body:
The best solution for this is a finite state machine. There are lots of tutorials on state machines, just google.

Finite state machines are a very important concept in coding. You will find the need for them everywhere. Do yourself a favour, and read up about them, practice them, understand them, love them. Understand when they will be useful, and when they are not. If you do not, you will be back here shortly, with another question, which could also be solved by a finite state machine.

I strongly recommend you use this task as a practice task for learning about finite state machines.

Note also that, in electrical circuits, you frequently get bounce - when you push a button, your arduino will see many "button presses" (from off, to on, back to off), until it settles down. See http://blog.kennyrasschaert.be/images/20140401/Bouncy_Switch.png for example. A state machine can also help you with this.

If you don't want to learn about FSMs, read on:

    initialise last_button_pressed to 0 (meaning no button pressed)
    if last_button_pressed>0
       if not(is_button_pressed(last_button_pressed) then
          last_button_pressed=0
    else (no button is pressed)
       for each button_to_check (1,2,3)
          if last_button_pressed=0 and is_button_pressed(button_to_check) then
             last_button_pressed=button_to_check


message:
code to force a gentle servo power up

So I am new to the board and looking for a source to answer an Arduino servo project's rough power up.  The project uses a pair of servos operating together to swing a small door.  I have been working with intro level sketches over the last few weeks. I have powered and re-powered my Arduino Uno several times with different codes and each time the unit is powered the two servo motors move to their last position at what appears to be full speed resulting in a rather jerky and jumpy power up.

What can you suggest in the code that would force the servo motors to gently move toward their new code starting position?  Like a 'warm up cycle'.

body:
I would recommend an [S curve][1] for the angular positioning of the door.

That should guarantee a smooth start and stop.

  [1]: https://en.wikipedia.org/wiki/Sigmoid_function


body:
You cannot do that with ordinary servos. This is because of the way the
communication protocol is built: the only thing a servo understands is a
command which in effect means “go to that position as fast as you can”.
You can achieve smooth movements by updating the requested position (the
so called “set point”) many times by tiny steps, but you still have the
problem at startup.

I see two possible solutions to your problem:

1. Make sure you know the position at which the servo was left when you
   powered down your Arduino. You can either arrange to leave it always
   at the same position, or you can store the last position in EEPROM
   before powering down. Then, at startup, you initialize the servo with
   that last known set point.

2. Use a special type of servo known as a [feedback
   servo](https://learn.adafruit.com/analog-feedback-servos/about-servos-and-feedback),
   or [convert a regular
   servo](http://www.instructables.com/id/Servo-Feedback-Hack-free/) to
   get a feedback. A feedback servo is a type of servo that tells you
   its actual position, so you can arrange for the initial set point to
   match that position.


message:
MatLab connection to Arduino using Bluetooth

I am attempting to send some information from MatLab to an Arduino Uno via Bluetooth with the following

MatLab program:

    b=Bluetooth('HC-06',1);
    fopen(b);
    for i=1:1:15
      fprintf(b,i);
      out(i) = fscanf(b,'%d');
    end
    fclose(b)

and Arduino program

    int matlabval=0;

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

    void loop() {
      if (Serial.available() > 0) {
        matlabval = Serial.read();
        Serial.println(matlabval);
      }
    }

the output  of arduino is

1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
10
10
10
11
10
12
10
13
10
14
10
15
10

The number 10 appears after each number. Why is that so?

Thanks in advance!

body:
As discussed in the comments, the "problem" seemed to be Matlab adding a "New Line" which is a decimal 10 in ASCII.

> asciitable.com Decimal 10 is the ASCII code for a "New Line" so it appears your Matlab send code will add a "New-line" after each sent value. – Paul Apr 14 at 8:15

>> thank you very match the problem is solved – abbas hussien 5 hours ago

*You might want to accept this answer so that this question gets "closed" and the site's statistics will be more accurate.
It will also avoid this question being bumped up by the system and people reading into something that has already been solved.*


message:
Arduino serial non-blocking

I'm writing an Arduino program to communicate with another module using RS485, so I need to control data flow with one pin. But when I set the pin to HIGH (line 88) it almost instantly falls (as you can see in the image, line 70). So my guess is that Arduino Serial.write() function is non-blocking, but I need it to be blocking [![enter image description here][1]][1]so the flow control pin stays high during whole packet transmit. Please help. Thank you.

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

body:
You are right: `Serial.write()` is non blocking: it puts the data in a
buffer and waits for an interrupt routine to send it through the UART.
If you want to wait for the transmission to complete, you can call
`Serial.flush()`.


message:
ESP8266 module cutting connection with PC via USB

My Arduino UNO is connected directly to the ESP8266 (01) WiFi module. The Red and Blue LED flashes and it seems to work properly. But when I connect the UNO to my computer, the module refreshes at irregular intervals and the PC produces sounds as that of ejecting and inserting a USB. I don't know whether this is caused due to low voltage supplied from the USB or some other reason. Please help me out...

body:
At which pins you connected the ESP8266?
The pins pin 0 (RX) an 1 (TX) are connectet internaly to the FTDI USB-to-TTL Serial chip.
If you using Serial.begin() to communicate with the ESP8266, you can't communicate with the pc at the same time.
Use SoftwareSerial to communicate with the ESP8266 an Serial to PC.

It is also recommed to feed the ESP8266 with an external 3.3V power supply and stabilize with an capacitor. This could  produces the sounds of ejecting and inserting a USB.


message:
Measuring The Distance Using GPS programmed with Arduino

Who among here have tried measuring the before and after distance traveled using gps? I'm going to use the code from TinyGPS library's distance_between command without constant value of latitude and longitude,

like this:

    static const float LONDON_LAT = 51.508131, LONDON_LON = -0.128002

I want to see that the first GPS latitude and longitude results is used as reference point.

How will I apply it on my code so that I could be able to get the distance I traveled? Please help me.

    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
     /*
       This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
     */
     static const int RXPin = 4, TXPin = 3;
     static const uint32_t GPSBaud = 4800;

      // The TinyGPS++ object
    TinyGPSPlus gps;

     // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin);

    void setup()
    {
     Serial.begin(115200);
     ss.begin(GPSBaud);

         Serial.println(F("FullExample.ino"));
         Serial.println(F("An extensive example of many interesting     TinyGPS++ features"));
      Serial.print(F("Testing TinyGPS++ library v. "));                    Serial.println(TinyGPSPlus::libraryVersion());
      Serial.println(F("by Mikal Hart"));
      Serial.println();
      Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars     Sentences Checksum"));
         Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
               Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
    }

    void loop()
    {
      static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

      printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
      printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
      printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
      printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
      printInt(gps.location.age(), gps.location.isValid(), 5);
      printDateTime(gps.date, gps.time);
      printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
      printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
      printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
      printStr(gps.course.isValid() ?        TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

      unsigned long distanceKmToLondon =
       (unsigned long)TinyGPSPlus::distanceBetween(
         gps.location.lat(),
         gps.location.lng(),
         LONDON_LAT,
         LONDON_LON) / 1000;
         printInt(distanceKmToLondon, gps.location.isValid(), 9);

         double courseToLondon =
        TinyGPSPlus::courseTo(
         gps.location.lat(),
         gps.location.lng(),
         LONDON_LAT,
         LONDON_LON);

       printFloat(courseToLondon, gps.location.isValid(), 7, 2);

       const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

       printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

       printInt(gps.charsProcessed(), true, 6);
       printInt(gps.sentencesWithFix(), true, 10);
       printInt(gps.failedChecksum(), true, 9);
       Serial.println();

       smartDelay(1000);

       if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial.println(F("No GPS data received: check wiring"));
       }

      // This custom version of delay() ensures that the gps object
      // is being "fed".
      static void smartDelay(unsigned long ms)
      {
      unsigned long start = millis();
      do
      {
       while (ss.available())
        gps.encode(ss.read());
        } while (millis() - start < ms);
        }

        static void printFloat(float val, bool valid, int len, int prec)
         {
       if (!valid)
       {
        while (len-- > 1)
        Serial.print('*');
        Serial.print(' ');
        }
        else
        {
       Serial.print(val, prec);
       int vi = abs((int)val);
       int flen = prec + (val < 0.0 ? 2 : 1); // . and -
       flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
       for (int i=flen; i<len; ++i)
       Serial.print(' ');
       }
       smartDelay(0);
      }

     static void printInt(unsigned long val, bool valid, int len)
     {
      char sz[32] = "*****************";
      if (valid)
      sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
       sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartDelay(0);
      }

      static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
      {
      if (!d.isValid())
       {
       Serial.print(F("********** "));
       }
       else
       {
       char sz[32];
       sprintf(sz, "d/d/d ", d.month(), d.day(), d.year());
       Serial.print(sz);
        }

        if (!t.isValid())
        {
        Serial.print(F("******** "));
        }
        else
        {
        char sz[32];
        sprintf(sz, "d:d:d ", t.hour(), t.minute(), t.second());
        Serial.print(sz);
        }

        printInt(d.age(), d.isValid(), 5);
        smartDelay(0);
        }

        static void printStr(const char *str, int len)
        {
        int slen = strlen(str);
        for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
        smartDelay(0);
        }

body:
This is where those dreaded maths classes come in.

You know - the ones where no one paid attention because you thought "Where in the real world would I ever want to know this stuff?" Well, right here is were you would want to know this stuff.

The distance between two points on a 2D plane (i.e., a map) can be looked at as two vertices of a right-angled triangle.

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

Going from Start to Finish you travel X degrees across the globe and Y degrees up or down it.  So you can calculate the number of degrees between the two points with simple pythagoras' theorem:

[![enter image description here][2]][2]

In C it's quite easy to do those calculations.  You can find X and Y by subtracting the two longitudes and scaling it for the logitudinal circumference of the Earth where you are. You can do the latitudes in a similar way:

    float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
    float Y = ((lat2 - lat1) * 24860) / 360.0

24901 is the circumference of the Earth at the equator, and 24860 is the circumference of the Earth going through both poles. Both are in miles, so the result will also be in miles. The numbers are different for the two directions because the Earth is not a perfect sphere. It is somewhat flattened at the poles, and is called an *oblate sphere*.

It doesn't matter which one you subtract from which since, when you square them, they will become positive anyway:

    float X2 = X * X;
    float Y2 = Y * Y;

Then you can get the square root:

    float Distance = sqrt(X2 + Y2);

So now you know how to calculate it without relying on some function in some library. It only takes a couple of lines of C code and you don't have to then know just how to use this unknown function provided by a library, and the theory will stand you in good stead for future similar projects.

Oh, and the code in full, in case you want it:

    float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
    float Y = ((lat2 - lat1) * 24860) / 360.0
    float X2 = X * X;
    float Y2 = Y * Y;
    float Distance = sqrt(X2 + Y2);

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


body:
I have been always frustrated from the missing double (64bit) type in Arduino world and hence the problem with properly calculating GPS distance, bearing and destination point.

The following library uses Float64 & Math64 libs and also adds some fast and very fast implementations of trigonometric functions and fast and regular versions of GPS GPS distance, bearing and destination point.

Feel free to use it - and any help in improving it is welcome !

https://github.com/vtomanov/Gps64


message:
Drop alpha character from serial input

I receive strings over the serial port like so:

VLT=53.0, AMP=-30.2, AHR=-10, SOC=98, TMP=136, STS=192

I want to reduce the use of string functions with the idea of dropping all non-digits, keeping numbers dot and comma, to get this:

53.0,-30.2,-10,98,136,192

in an array and simple read [0], [1], etc.

Regular expressions would be idea, but do not exist like in PERL.
Any hint would be much appreciated.

Relevant code used:

        char inByte = SerialPortOne.read(); // read byte
        strRecordIn.concat(inByte);         // add byte to receive buffer
        for (int i = 0; i <= 3; i++) {    // VLT, AMP, AHR, SOC
        strWord = getValue(strRecordIn, ',', i);  // get data item from RecordIn array
          strWord.remove(0, 4);           // remove field identifier (1st 3 char plus =)
          strRecordOut += ',';            // add delimiter
          strRecordOut += strWord;        // add value
          strWord = "";                   // reset strWord
        }

Ideally:

        char inByte = SerialPortOne.read(); // read byte
        if (inByte = [%d.,]+) {
          strRecordIn.concat(inByte);       // add byte to receive buffer
        }

body:
If you just want to remove the letters:

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

    #include <ctype.h>

    char inByte = SerialPortOne.read();  // read byte
    if (!isalpha(inByte)) {              // not letter
        strRecordIn.concat(inByte);      // add byte to receive buffer
    }

Or you may test it for `isdigit()` and explicitly compare to `','` and
`'.'`:

    if (isdigit(inByte) || inByte == '.' || inByte == ',') {
        strRecordIn.concat(inByte);      // add byte to receive buffer
    }

C.f. the [documentation of
<ctype.h>](http://www.nongnu.org/avr-libc/user-manual/group__ctype.html).


message:
Breaking a switch case from an ISR

I'm struggling with something. My CPU sits in a switch case state machine like this:

    switch(expression) {

       case constant-expression_1  :
          statement(s);
          break; /* optional */

       case constant-expression_2  :
          statement(s);
          break; /* optional */

       /* you can have any number of case statements */
       default : /* Optional */
       statement(s);
    }

I have an interrupt that occurs on a button press. In the interrupt, I change the switch expression to the case I want to go next, like this:

    void ISR(void){
       expression = constant-expression_2;
    }

After the interrupt has been handled, I want the CPU to return directly to the case being switched to, and to not continue where it left off.

Does anyone have any good ideas on how to implement this, if it's possible? I'd prefer to not have to wait for the code to finish what was happening in the previous case before going to the one being switched to.

Thanks in advance!

body:
Most of the time this isn't a problem, because code normally runs pretty fast. The problem, most of the time, is the use of `delay`s. What I did was use my own delay function that checks if the expression has changed, and if so, immediately returns.

Below is my code. I had to modify it a bit, so it might not work out of the box, but will give you the idea as to how.

    volatile byte expression;
    volatile boolean expressionChanged = false;

    switch(expression) {

       case constant-expression_1  :
          statement(s);
          myDelay(1000);
          statement(s);
          break; /* optional */

       case constant-expression_2  :
          statement(s);
          myDelay(500);
          statement(s);
          break; /* optional */

       /* you can have any number of case statements */
       default : /* Optional */
          statement(s);
    }

    void myDelay(int ms)
    {
        uint32_t start = micros();
        while (ms > 0 && !expressionChanged)
        {
            //yield();not implemented in arduino
            if ( (micros() - start) >= 1000)
            {
                ms--;
                start += 1000;
            }
        }
    }

    void ISR(void){
       expression = constant-expression_2;
       expressionChanged = true;
    }


body:
It is certainly possible, although I do not think there is any _clean_
way of doing it...

Here is an idea that **may** work: right before the switch statement,
you save the current context with [the `setjmp()`
function](http://www.nongnu.org/avr-libc/user-manual/group__setjmp.html).
Then, in the ISR, you restore that context with `longjmp()`. This is
kind of like a goto statement that works across functions:

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

    #include <setjmp.h>

    jmp_buf env;

    ISR(FOO_vect) {
        expression = ...;
        longjmp(env, 1);  // go to start of loop
    }

    void loop() {
        setjmp(env);  // landing point from ISR exit
        switch (expression) {
            ...
        }
    }

Notice that the normal exit sequence of an ISR (the `reti` instruction)
re-enables the interrupts. Since we are skipping this exit sequence, <s>we
have to enable them explicitly upon return from `setjmp()`</s>
interrupts are re-enabled not by the `reti` instruction but by `longjmp()`
restoring the CPU's status register.

**Warning**: This is a (very dirty) hack that I have _not tested_. If I
were to use this trick, I would first:

 1. Carefully examine the generated assembly to convince myself it does
    the right thing.
 2. Test, test, test...

In case of problems, debugging this may be harder than just testing the
expression inside every slow function you have.

**Addendum**: Although I am saying that there is no clean way of doing
what you intend, there certainly is a clean way of achieving the same
end result: just make sure your switch statements return fast. My
preferred way of doing this would be to make sure no function ever
waits. For example:

* A routine reading sensors would not wait for them to respond. Instead,
  it would return immediately if no reading is available. If a reading
  _is_ available, it would retrieve it, send a query to the next sensor
  in the list, then return.
* A communication routine would not wait for complete messages. Instead,
  it would return immediately if no byte is available. If a byte is
  available, it would buffer it and return. Unless it's the last byte of
  a complete message, in which case it would process the message.

Obviously this could require a heavy refactoring of your code, probably
using finite state machines (see for example the tutorials
[here](https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/)
and [here](https://www.sparkfun.com/news/1801)). It may be easier to
just test whether the expression has changed inside every busy-wait loop
you have, as recommended by Gerben's and Nick's answers.


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

First, put your major processing into functions. That looks better anyway. eg.

    switch(expression) {

       case constant-expression_1  :
          function1 ();
          break; /* optional */

       case constant-expression_2  :
          function2 ();
          break; /* optional */

       /* you can have any number of case statements */
       default : /* Optional */
          function_default ();
    }

Now inside your functions do a `return` if you notice the expression has changed. This will get you out of any number of nested loops. For your 30 sensors, for example, you can now have a loop.

    void function1 ()
      {
      for (int i = 0; i < 30; i++)
        {
        if (expression_changed)
           return;
        // take sensor reading
        }
      }  // end of function1

Also, as Gerben suggested, replace any `delay` calls with a function that does the delay, however which ends early if the expression changes. It can return a boolean to let you know this happened. eg.

    boolean myDelay(int ms)
      {
        uint32_t start = micros();
        while (ms > 0)
        {
            if (expression_changed)
               return true;   // early return
            if ( (micros() - start) >= 1000)
            {
                ms--;
                start += 1000;
            }
        }
      return false;   // normal return
      }

Now any function that needs delays can use that, like this:

    void function2 ()
      {
      do_something ();
      if (myDelay (1000))
         return;   // bail out
      do_something_else ();
      }  // end of function1

> My problem is, one of my cases includes a communication transceiver method, which can take a lot of time to get through

There must be logical spots where you can just test the expression and do a `return` (preferably cleaning up anything that needs it) when required.


message:
Arduino Nano USB Serial Bypass

I have a Nano clone here, that sporadically fails to get detected by my banana pi. This is annoying, because it works for days and hours, but fails to work randomly.

The Nano gets it's own power via `VIN` and thus should have enough power.

I thought of bypassing the FTDI and make a Serial connection via 2 Wires. Alternatively: Is there a way to force the arduino to use external Power over USB. I have the feeling, the the arduino wrongly decides, that USB is the better power source and uses it, causing the errors ( `device not accepting address 21, error -62` )

P.S.: There is also a touch-screen connected to the banana pi via USB. Whatever port I use, It works and never failed. Just the Nano fails from time to time.

body:
To answer this question

The arduino in question was broken. Shortly after asking I was not even able to connect it to my PC successfully. I replaced it with a new one and everything runs smoothly now for months.

Since this unit survived a whole product development-process I am not surprised at all. In fact I had three and expected one to get killed in action.


message:
Defining an NFC tag as NDEF using the Arduino Uno and the PN532 NFC module

I bought a bunch of blank Mifare Classic NFC cards and I'd like to write NDEF records to them using my Arduino Uno. When I read them using my Uno and a PN532 NFC module using [Don's NDEF library](https://github.com/don/NDEF/blob/master/examples/ReadTagExtended/ReadTagExtended.ino) however, it tells me they're not NDEF formatted.

Is there any way to define my NFC tags as NDEF using just the PN532 module and an Arduino Uno? (My Android phone doesn't support NFC.)

body:
I found the answer to my own question right after posting it, while going through the examples included in the library above:

The library contains an example named "FormatTag" which does exactly what I was looking for.


message:
Controlling Enable Function on MicroStepper Driver

I'm having trouble using the ENABLE pin on my microstepper driver, I'm not sure of the exact model but it looks exactly like the one pictured here

[Microstepper Driver][1]

  [1]: http://www.driver-motor.com/UploadFile/ProductImage/1/5/20090328230757_照片-005.jpg

Here's my code:

    #define MAX_LEN 8
    #define MIN_INCREMENT 0.5
    #define LIMIT_SWITCH 3
    #define ENABLE 10
    float buoyancymass = 4401.425;
    float centrebuoyancy = 14.164;
    float mainarm = 14.3;
    float nosearm = 1.8;
    float adc = 11.4;
    float meanadc = 22.65;
    volatile byte enable_state = LOW;

    #include <Stepper.h>

    const int stepsPerRevolution = 1600;  // change this to fit the number of steps per revolution
    // for your motor

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    int stepCount = 0;         // number of steps the motor has taken
    float stepinch = 0.00524; // 1 step = x"

    void setup() {
      // initialize the serial port:
      Serial.begin(9600);
      pinMode(LIMIT_SWITCH, INPUT_PULLUP);
      pinMode(ENABLE, OUTPUT);
      //enable motor
      digitalWrite(ENABLE, enable_state);
      //interrupt
      attachInterrupt(digitalPinToInterrupt(LIMIT_SWITCH), limitbrake, FALLING);
      // set the speed
      myStepper.setSpeed(30);
    }

    void limitbrake() {
      digitalWrite(ENABLE, !enable_state);
    }

The problem I'm noticing is that when I set the `pinMode(ENABLE,OUTPUT);` my stepper doesn't draw current and therefor, doesn't drive. This occurs regardless of whether I set my `enable_state` to HIGH or LOW.

Funny enough, when I set it to `pinMode(ENABLE,INPUT);` it does draw current and drive the motor, but unfortunately my limit switch which I've attached an interrupt to doesn't disable the motor when its pressed.

Before you ask, I've tested the enable pin on my driver and my limit switch circuitry in other programs and they both work. I'm just having trouble with putting it together.

Here is the rest of my code if you were wondering.

    float calc_margin(float pos, float mass) {
      // calculate margin
      Serial.print("Distance: ");Serial.println(pos);
      float batterymoment = mass*pos;
      Serial.println(batterymoment);
      float totalmass = mass + 12404;
      Serial.println(totalmass);
      float totalmoment = 149650+batterymoment;
      Serial.println(totalmoment);
      float buoyancymoment = buoyancymass*centrebuoyancy;
      Serial.println(buoyancymoment);
      float wheelmoment = totalmoment - buoyancymoment;
      Serial.println(wheelmoment);
      float wheelweight = totalmass - buoyancymass;
      Serial.println(wheelweight);
      float cgwheels = wheelmoment/wheelweight;
      Serial.println(cgwheels);
      float maindistance = mainarm - cgwheels;
      Serial.println(maindistance);
      float nosedistance = cgwheels - nosearm;
      Serial.println(nosedistance);
      float mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
      Serial.println(mainmass);
      float nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
      Serial.println(nosemass);
      float mainmoment = mainmass*mainarm;
      Serial.println(mainmoment);
      float nosemoment = nosemass*nosearm;
      Serial.println(nosemoment);
      float netmoment = buoyancymoment+(mainmoment*2)+(nosemoment*2);
      Serial.println(netmoment);
      float netcg = netmoment/totalmass;
      Serial.println(netcg);
      float staticmargin = adc - netcg;
      Serial.println(staticmargin);
      float answer = staticmargin/meanadc;
      Serial.println(answer);
      float percentage = answer*100;
      Serial.print(percentage); Serial.println("%");
      float result = answer;
      return result;
    }

    boolean check_margin(float test_margin) {
      if (test_margin > -0.04 && test_margin < -0.02)
        return true;
      return false;
    }

    float armcalc(float mass) {
      for(float x=0;x<MAX_LEN;x+=MIN_INCREMENT) {
        // calculate margin
        float margin = calc_margin(x,mass);
        if (check_margin(margin)) {
          return x;
        }
      }
      return -1;
    }

    float stepcalc(float arm){
      int arminch = arm*12;
      float numberofsteps = arminch/stepinch;
      int result = numberofsteps;
      Serial.print("Calculated steps: "); Serial.println(result);
      return result;
    }

    void loop() {
      // read input
      Serial.println("Enter mass: ");
      while (!Serial.available());
      float mass = Serial.parseFloat();
      float arm = armcalc(mass);
      if (arm < 0) {
        // Error message
        Serial.println("Error!");
        return;
      }
      Serial.print("Arm distance is "); Serial.println(arm);
      // step
      const int steplength = (int) stepcalc(arm);
      Serial.print("Number of steps is "); Serial.println(steplength);
      myStepper.step(-steplength);

      while(1);

    }

body:
These drivers differ from the H-Bridge-design [described here][1]. You don't need to generate pulses for the coils, as you would do with a classic H-Bridge.

1. Connect your motor to `A+`, `A-`, `B+`, `B-` (a is one coil, b the other)

2. Connect Power (guess 12+ volts, mine take up to 48V) to `GND` and `V+`

3. Either connect 5V to `ENA+(+5V)` or a free arduino Pin and `ENA-(ENA)` to GND. This pin enables/disables the driver. If no input is present at this pin, the driver will not work.

4. Connect `DIR+(+5V)` to a free arduino pin and `DIR-(DIR)` to `GND`. This pin controls the direction. `HIGH` makes the motor turn right, while `LOW` on this pin makes the motor turn left.

5. Connect `PUL+(+5V)` to a free arduino pin and `PUL-(PUL)` to `GND`. This pin controls the speed. The more pulses/second one applies, the faster the motor turns. (Up to a limit, of course).

Sketch should be easy.

**Plus**: You could turn around the control connections, by hardwiring all `+5V` pins to 5V and use `INPUT_PULLUP` to switch the current flow on the negative lines. I know that these drivers are optical isolated and draw as little as 10 mA from a pin, if at all. So you should be safe.

  [1]: http://www.arduino.cc/en/Reference/StepperBipolarCircuit


message:
Control speed of linear actuator servo

I have a [linear actuator][1] that I want to be able to slow down. Right now, the shaft moves too quickly. I'm not sure how to do this. I was looking into `varSpeedServo.h` library but couldn't implement it.

<!-- language: c -->

    //Includes
    #include <Servo.h>

    //Defines
    #define LINEARACTUATORPIN 9        //Linear Actuator Digital Pin

    const int button1Pin = 4;     // the number of the pushbutton pin

    // variables will change:
    int button1State = 0;         // variable for reading the pushbutton status

    Servo LINEARACTUATOR;  // create servo objects to control the linear actuator

    int linearValue = 10000;   //current positional value being sent to the linear actuator.

    void setup()
    {
      //initialize servo/linear actuator objects
      LINEARACTUATOR.attach(LINEARACTUATORPIN, 1050, 2000);      // attaches/activates the linear actuator as a servo object

      // initialize the pushbutton pin as an input:
      pinMode(button1Pin, INPUT);

      //use the writeMicroseconds to set the linear actuators to their default positions
      LINEARACTUATOR.writeMicroseconds(linearValue);

    }

    void loop()
    {

      // if the pushbutton is pressed set the linear value
      button1State = digitalRead(button1Pin);
      if (button1State == HIGH) {
        // set the position value
        delay(2000);
        linearValue = 1050;

      }

        if (button1State == LOW) {
        // set the position value
        linearValue = 2000;
      }

      //use the writeMicroseconds to set the actuator to the new position
      LINEARACTUATOR.writeMicroseconds(linearValue);
    delay(3000);
    }

  [1]: http://www.firgelli.com/Firgelli_Technologies_PQ12_R_p/pq12-r.htm

body:
Have you tried something like the following?

    #define STEP 50

    void loop()
    {

      // if the pushbutton is pressed set the linear value
      button1State = digitalRead(button1Pin);
      if (button1State == HIGH) {
        // set the position value
        if (linearValue > 1050)
           linearValue = max(linearValue-STEP,1050) ;

      }

        if (button1State == LOW) {
        // set the position value
        if (linearValue < 2000)
           linearValue = min(linearValue+50,2000) ;
      }

      //use the writeMicroseconds to set the actuator to the new position
      LINEARACTUATOR.writeMicroseconds(linearValue);
      delay(100);
    }

By changing the STEP value (or the delay in the next-to-last line) you can change the speed of the servo.


message:
Can a 9V battery be used as a backup power supply (to Arduino Uno) while plugged directly into Vin and ground?

Sorry if this has been asked before, but I've read tons of threads and it seems the answer is only implied on a couple of occasions.

I'm an electrical noob, but I understand that a 9v battery plugged into a wall wort with a diode would serve as a battery backup if the power was cut from the wall wort.  I also understand that Vin on an arduino already has a diode to do this.

I'm currently powering a temp/humidity that is dumping data into MySQL using a standard A-B USB cable and 5V DC USB power supply.  I'd like to incorporate a 9V battery plugged into Vin and ground, so that if DC power turns off, I can dump the data onto the SD card instead (since my MySQL server may or not be running during an outage).

body:
My problem with that is that the other side of the diode on the Arduino is normally powered up. So for example if you have a 12V supply in the power jack you'll have 11.3V at Vin (because of the diode drop). Thus you are pumping 11.3V into your 9V battery which won't be designed to handle it. It will probably get hot and explode.

You would need *another* diode specifically between the battery and Vin. And make sure that Vin is at least 10V so that the normal mains power does not charge the battery.

Bear in mind a 9V battery doesn't have much capacity. With the power LED on,  taking sensor readings, and sending data via Ethernet (if that is what you are doing) you may have only bought yourself 15 minutes.

I have a post about a [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) which runs all the time from 3 x AA batteries. I think the batteries need replacing about every two years. The data is written to an SD card which you remove and plug into your computer when you want to.

---

> when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery

Looks like I misread the question. @mwwalk is quite right. If you supply more than 6.6V through Vin then the circuitry switches the USB off. See here:

[![Uno power switching][1]][1]

Vin is provided by the power jack (after a diode which drops it by 0.7V) - see blue ellipse. In any case (power jack or not) Vin goes through a voltage divider (two 10k resistors to the left of the red circle). This is compared to the output of the 3.3V voltage regulator. Therefore `GATE_CMD` is HIGH if Vin exceeds 6.6V. This turns **off** the MOSFET (green circle) and disconnects the USB power.

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


body: No, when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery, not usb and the battery will quickly be depleted.