message:
Can't operate relay's functionality in ISR function - SOLVED

In recent project, I have to operate my relay based on falling edge of Square wave. Here, falling edge detect by using interrupt. So, whenever Arduino detect falling edge using interrupt, ISR function called and in ISR function I perform my relay's functionality. Means whenever ISR function called, relay turn on for some milliseconds and then turn off. But whenever I connect relay, it's not operate. Here, relay connected with pin 13, so Arduino attached led blinking but not with full brightness. I don't understand why it's happened. Give me some suggestions.

Here, it's my code.

     //----------------------------For MAP calculation----------------------------//

    const int kPinMAP = A0;       // MAP / Analog Pin A0

    float MAP;

    float MAP_MIN = 0.85;
    float MAP_MAX = 1.90;

    float LOAD_MIN_MAP_MIN = 2.00;
    float LOAD_MAX_MAP_MIN = 15.00;

    float LOAD_MIN_MAP_MAX = 10.00;
    float LOAD_MAX_MAP_MAX = 85.00;

    float mMAPmin;
    float mMAPmax;

    float yMAPmin;
    float yMAPmax;

    float mMAP;

    float yMAP;

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

    //----------------------------For TPS calculation----------------------------//

    const int kPinTPS = A1;       // TPS / Analog Pin A1

    float TPS;

    float TPS_MIN = 0.00;
    float TPS_MAX = 5.00;

    float LOAD_MIN_TPS_MIN = 2.00;
    float LOAD_MAX_TPS_MIN = 10.00;

    float LOAD_MIN_TPS_MAX = 15.00;
    float LOAD_MAX_TPS_MAX = 85.00;

    float mTPSmin;
    float mTPSmax;

    float yTPSmin;
    float yTPSmax;

    float mTPS;

    float yTPS;

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

    //----------------------------For LOAD calculation---------------------------//

    int LOAD_MIN = 2;
    int LOAD_MAX = 100;

    float injTime_MIN_LOAD_MIN = 4.00;
    float injTime_MAX_LOAD_MIN = 4.60;

    float injTime_MIN_LOAD_MAX = 8.06;
    float injTime_MAX_LOAD_MAX = 14.86;

    float LOAD;

    float mLOADmin;
    float mLOADmax;

    float yLOADmin;
    float yLOADmax;

    float mLOAD;

    float yLOAD;

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

    //----------------------------For RPM calculation----------------------------//

    const int kPinRPM = 3;        // RPM / Digital Pin 3
    const int RPMInterrupt = 1;   // RPM's interrrupt pin

    //--------------Pulse per revolution = 2 * cyclinders / cycles--------------//

    byte engineCylinders = 2;         // Engine cylinders = 4;
    byte engineCycles = 4;            // Engine cycle = 2
    int refreshInterval = 750;        // Milliseconds between sensor updates
    unsigned long previousMillis = 0;
    volatile int RPMpulses = 0;
    int RPM, Final_RPM;

    int RPM_MIN = 400;
    int RPM_MAX = 6000;

    float injTime_MIN_RPM_MIN = 4.00;
    float injTime_MAX_RPM_MIN = 8.06;

    float injTime_MIN_RPM_MAX = 4.60;
    float injTime_MAX_RPM_MAX = 14.86;

    float mRPMmin;
    float mRPMmax;

    float yRPMmin;
    float yRPMmax;

    float mRPM;

    float yRPM;

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

    //------------------------For GAS PRESSURE calculation-----------------------//

    const int kPinPressureGAS = A2;      // GAS Pressure / Analog Pin A2
    float GAS_Pressure;

    float minPosVolGas = 0.00;
    float maxPosVolGas = 2.50;

    float minInjPerPos = 0.35;
    float maxInjPerPos = 0.00;

    float minNagVolGas = 2.50;
    float maxNagVolGas = 5.00;

    float minInjPerNag = 0.00;
    float maxInjPerNag = 0.25;

    float mGasPos, mGasNag;
    float yGasPos, yGasNag;

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

    //----------------------For INJECTION TIME calculation-----------------------//

    float yInjTime, injTime, gasInjTime;
    const int kPinInj = 13;
    int temp = 0;

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

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

      pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
      attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

      pinMode(kPinInj, OUTPUT);
      //digitalWrite(kPinInj, HIGH);
    }

    void loop()
    {
      //----------------------------MAP----------------------------//

      MAP = analogRead(A0) * (5.0 / 1023.0);

      mMAPmin = (LOAD_MAX_MAP_MIN - LOAD_MIN_MAP_MIN) / (MAP_MAX - MAP_MIN);

      //Serial.print("mMAPmin : ");
      //Serial.println(mMAPmin);

      yMAPmin = mMAPmin * (MAP - MAP_MIN) + LOAD_MIN_MAP_MIN;

      //Serial.print("MAP : ");
      //Serial.print(MAP);
      //Serial.print("\t");
      //Serial.print("LOAD : ");
      //Serial.println(yMAPmin);

      mMAPmax = (LOAD_MAX_MAP_MAX - LOAD_MIN_MAP_MAX) / (MAP_MAX - MAP_MIN);

      //Serial.print("mMAPmax : ");
      //Serial.println(mMAPmax);

      yMAPmax = mMAPmax * (MAP - MAP_MIN) + LOAD_MIN_MAP_MAX;

      //Serial.print("MAP : ");
      //Serial.print(MAP);
      //Serial.print("\t");
      //Serial.print("LOAD : ");
      //Serial.println(yMAPmax);

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

      //----------------------------TPS----------------------------//

      TPS = analogRead(A1) * (5.0 / 1023.0);

      mTPSmin = (LOAD_MAX_TPS_MIN - LOAD_MIN_TPS_MIN) / (TPS_MAX - TPS_MIN);

      //Serial.print("mTPSmin : ");
      //Serial.println(mTPSmin);

      yTPSmin = mTPSmin * (TPS - TPS_MIN) + LOAD_MIN_TPS_MIN;

      //Serial.print("TPS : ");
      //Serial.print(TPS);
      //Serial.print("\t");
      //Serial.print("LOAD : ");
      //Serial.println(yTPSmin);

      mTPSmax = (LOAD_MAX_TPS_MAX - LOAD_MIN_TPS_MAX) / (TPS_MAX - TPS_MIN);

      //Serial.print("mTPSmax : ");
      //Serial.println(mTPSmax);

      yTPSmax = mTPSmax * (TPS - TPS_MIN) + LOAD_MIN_TPS_MAX;

      //Serial.print("TPS : ");
      //Serial.print(TPS);
      //Serial.print("\t");
      //Serial.print("LOAD : ");
      //Serial.println(yTPSmax);

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

      //----------------TPS/MAP CALLIBRATION / LOAD----------------//

      mTPS = (yMAPmax - yMAPmin) / (TPS_MAX - TPS_MIN);

      //Serial.print("mTPS : ");
      //Serial.println(mTPS);

      yTPS = mTPS * (TPS - TPS_MIN) + yMAPmin;

      Serial.print("TPS : ");
      Serial.print(TPS);
      Serial.print("\t");
      //Serial.print("LOAD : ");
      //Serial.print(yTPS);
      //Serial.print("\t");

      mMAP = (yTPSmax - yTPSmin) / (MAP_MAX - MAP_MIN);

      //Serial.print("mMAP : ");
      //Serial.println(mMAP);

      yMAP = mMAP * (MAP - MAP_MIN) + yTPSmin;

      Serial.print("MAP : ");
      Serial.print(MAP);
      Serial.print("\t");
      //Serial.print("LOAD : ");
      //Serial.print(yMAP);
      //Serial.print("\t");

      LOAD = (yTPS + yMAP) / 2;
      Serial.print("Final LOAD : ");
      Serial.print(LOAD);
      Serial.print("\t");

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

      //----------------------------LOAD---------------------------//

      mLOADmin = (injTime_MAX_LOAD_MIN - injTime_MIN_LOAD_MIN) / (LOAD_MAX - LOAD_MIN);

      //Serial.print("mLOADmin : ");
      //Serial.println(mLOADmin);

      yLOADmin = mLOADmin * (LOAD - LOAD_MIN) + injTime_MIN_LOAD_MIN;

      //Serial.print("LOAD : ");
      //Serial.print(LOAD);
      //Serial.print("\t");
      //Serial.print("injTime : ");
      //Serial.println(yLOADmin);

      mLOADmax = (injTime_MAX_LOAD_MAX - injTime_MIN_LOAD_MAX) / (LOAD_MAX - LOAD_MIN);

      //Serial.print("mLOADmax : ");
      //Serial.println(mLOADmax);

      yLOADmax = mLOADmax * (LOAD - LOAD_MIN) + injTime_MIN_LOAD_MAX;

      //Serial.print("LOAD : ");
      //Serial.print(LOAD);
      //Serial.print("\t");
      //Serial.print("injTime : ");
      //Serial.println(yLOADmax);

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

      //----------------------------RPM----------------------------//

      if(millis() - previousMillis > refreshInterval)
      {
        previousMillis = millis();
        RPM = getRPM();
      }

      mRPMmin = (injTime_MAX_RPM_MIN - injTime_MIN_RPM_MIN) / (RPM_MAX - RPM_MIN);

      //Serial.print("mRPMmin : ");
      //Serial.println(mRPMmin);

      yRPMmin = mRPMmin * (RPM - RPM_MIN) + injTime_MIN_RPM_MIN;

      //Serial.print("RPM : ");
      //Serial.print(RPM);
      //Serial.print("\t");
      //Serial.print("injTime : ");
      //Serial.println(yRPMmin);

      mRPMmax = (injTime_MAX_RPM_MAX - injTime_MIN_RPM_MAX) / (RPM_MAX - RPM_MIN);

      //Serial.print("mRPMmax : ");
      //Serial.println(mRPMmax);

      yRPMmax = mRPMmax * (RPM - RPM_MIN) + injTime_MIN_RPM_MAX;

      //Serial.print("RPM : ");
      //Serial.print(RPM);
      //Serial.print("\t");
      //Serial.print("injTime : ");
      //Serial.println(yRPMmax);

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

      //-----------LOAD/RPM CALLIBRATION / INJECTION TIME----------//

      mLOAD = (yRPMmax - yRPMmin) / (LOAD_MAX - LOAD_MIN);

      //Serial.print("mLOAD : ");
      //Serial.println(mLOAD);

      yLOAD = mLOAD * (LOAD - LOAD_MIN) + yRPMmin;

      Serial.print("LOAD : ");
      Serial.print(LOAD);
      Serial.print("\t");
      //Serial.print("injTime : ");
      //Serial.print(yLOAD);
      //Serial.print("\t");

      mRPM = (yLOADmax - yLOADmin) / (RPM_MAX - RPM_MIN);

      //Serial.print("mRPM : ");
      //Serial.println(mRPM);

      yRPM = mRPM * (RPM - RPM_MIN) + yLOADmin;

      Serial.print("RPM : ");
      Serial.print(RPM);
      Serial.print("\t");
      //Serial.print("injTime : ");
      //Serial.print(yRPM);
      //Serial.print("\t");

      yInjTime = (yLOAD + yRPM) / 2;
      Serial.print("Final injTime : ");
      Serial.print(yInjTime);
      Serial.print("\t");

      injTime = (yInjTime * 1000) / 1000;
      Serial.print("Injection Time : ");
      Serial.print(injTime);
      Serial.print("\t");

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

      //------------------------GAS_PRESSURE-----------------------//

      GAS_Pressure =  analogRead(A2) * (5.0 / 1023.0);
      Serial.print("GAS Pressure : ");
      Serial.print(GAS_Pressure);
      Serial.print("\t");

      mGasPos = (maxInjPerPos - minInjPerPos) / (maxPosVolGas - minPosVolGas);

      yGasPos = mGasPos * (GAS_Pressure - minPosVolGas) + minInjPerPos;
      //Serial.print("InjTimeY1 : ");
      //Serial.print(yGasPos);
      //Serial.print("\t");

      mGasNag = (maxInjPerNag - minInjPerNag) / (maxNagVolGas - minNagVolGas);

      yGasNag = mGasNag * (GAS_Pressure - minNagVolGas) + minInjPerNag;
      //Serial.print("InjTimeY2 : ");
      //Serial.print(yGasNag);
      //Serial.print("\t");

      if(GAS_Pressure >= 0.00 && GAS_Pressure < 2.50)
      {
        gasInjTime = injTime + (injTime * yGasPos);
        Serial.print("GASinjTimePos : ");
        Serial.print(gasInjTime);
        Serial.print("\n");
      }

      if(GAS_Pressure >= 2.50 && GAS_Pressure <= 5.00)
      {
        gasInjTime = injTime - (injTime * yGasNag);
        Serial.print("GASinjTimeNag : ");
        Serial.print(gasInjTime);
        Serial.print("\n");
      }
      //-----------------------------------------------------------//

    }

    //----------------------------RPM----------------------------//

    void countRPM()
    {
      RPMpulses++;

      digitalWrite(kPinInj, HIGH);
      delay(gasInjTime);
      digitalWrite(kPinInj, LOW);
    }

    int getRPM()
    {
      Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
      RPMpulses = 0;
      Final_RPM = min(99999, Final_RPM);
      return Final_RPM;
    }
    //-----------------------------------------------------------//

After suggestion of Majenko and some modification(done by me) my updated code working fine. My relay operate very well. My OUTPUT Pin 13 Square Wave synchronized with INPUT Pin 2 Square Wave Here is my updated code :

    //----------------------------For MAP calculation----------------------------//
    float MAP_MIN = 0.85;
    float MAP_MAX = 1.90;

    int LOAD_MIN_MAP[] = {2, 10};
    int LOAD_MAX_MAP[] = {15, 85};

    float mMAP[2] = {};
    float yMAP[2] = {};

    int i, j, a;
    float MAP, mFinalMAP, yFinalMAP;

    //----------------------------For TPS calculation----------------------------//
    float TPS_MIN = 0.00;
    float TPS_MAX = 5.00;

    int LOAD_MIN_TPS[] = {2, 15};
    int LOAD_MAX_TPS[] = {10, 85};

    float mTPS[2] = {};
    float yTPS[2] = {};

    int k, l, b;
    float TPS, mFinalTPS, yFinalTPS;

    //----------------------------For LOAD calculation---------------------------//
    int LOAD_MIN = 2;
    int LOAD_MAX = 100;

    float injTime_MIN_LOAD[] = {4.00, 8.06};
    float injTime_MAX_LOAD[] = {4.60, 14.86};

    float mLOAD[2] = {};
    float yLOAD[2] = {};

    int m, n, c;
    float LOAD, mFinalLOAD, yFinalLOAD;

    //----------------------------For RPM calculation----------------------------//
    const int kPinRPM = 3;        // RPM / Digital Pin 3
    const int RPMInterrupt = 1;   // RPM's interrrupt pin
    byte engineCylinders = 2;         // Engine cylinders = 4;
    byte engineCycles = 4;            // Engine cycle = 2
    int refreshInterval = 750;        // Milliseconds between sensor updates
    unsigned long previousMillis = 0;
    volatile int RPMpulses = 0;
    int RPM, Final_RPM;

    int RPM_MIN = 400;
    int RPM_MAX = 6000;

    float injTime_MIN_RPM[] = {4.00, 4.60};
    float injTime_MAX_RPM[] = {8.06, 14.86};

    float mRPM[2] = {};
    float yRPM[2] = {};

    int o, p, d;
    float mFinalRPM, yFinalRPM;

    //------------------------For GAS PRESSURE calculation-----------------------//
    float minPosVolGas = 0.00;
    float maxPosVolGas = 2.50;

    float minInjPerPos = 0.35;
    float maxInjPerPos = 0.00;

    float minNagVolGas = 2.50;
    float maxNagVolGas = 5.00;

    float minInjPerNag = 0.00;
    float maxInjPerNag = 0.25;

    float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

    //----------------------For INJECTION TIME calculation-----------------------//
    float yInjTime, injTime, gasInjTime;
    volatile uint32_t kInjTime = 0;

    const int kPinInj = 13;

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

      pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
      attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

      pinMode(kPinInj, OUTPUT);
    }

    void loop()
    {
      //----------------------------MAP----------------------------//

      MAP = analogRead(A0) * (5.0 / 1023.0);

      for(a = 0; a < 2; a++)
      {
        mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
        yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
      }

      //----------------------------TPS----------------------------//

      TPS = analogRead(A1) * (5.0 / 1023.0);

      for(b = 0; b < 2; b++)
      {
        mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
        yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
      }

      //----------------TPS/MAP CALLIBRATION / LOAD----------------//

      mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
      yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

      mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
      yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

      LOAD = (yFinalTPS + yFinalMAP) / 2;

      //----------------------------LOAD---------------------------//

      for(c = 0; c < 2; c++)
      {
        mLOAD[m] = (injTime_MAX_LOAD[c] - injTime_MIN_LOAD[c]) / (LOAD_MAX - LOAD_MIN);
        yLOAD[n] = mLOAD[m] * (LOAD - LOAD_MIN) + injTime_MIN_LOAD[c];
      }

      //----------------------------RPM----------------------------//

      if(millis() - previousMillis > refreshInterval)
      {
        previousMillis = millis();
        RPM = getRPM();
      }

      for(d = 0; d < 2; d++)
      {
        mRPM[o] = (injTime_MAX_RPM[d] - injTime_MIN_RPM[d]) / (RPM_MAX - RPM_MIN);
        yRPM[p] = mRPM[o] * (RPM - RPM_MIN) + injTime_MIN_RPM[d];
      }

      //-----------LOAD/RPM CALLIBRATION / INJECTION TIME----------//

      mFinalLOAD = (yRPM[1] - yRPM[0]) / (LOAD_MAX - LOAD_MIN);
      yFinalLOAD = mFinalLOAD * (LOAD - LOAD_MIN) + yRPM[0];

      mFinalRPM = (yLOAD[1] - yLOAD[0]) / (RPM_MAX - RPM_MIN);
      yFinalRPM = mFinalRPM * (RPM - RPM_MIN) + yLOAD[0];

      yInjTime = (yFinalLOAD + yFinalRPM) / 2;
      injTime = (yInjTime * 1000) / 1000;

      //------------------------GAS_PRESSURE-----------------------//

      GAS_Pressure =  analogRead(A2) * (5.0 / 1023.0);

      mGasPos = (maxInjPerPos - minInjPerPos) / (maxPosVolGas - minPosVolGas);
      yGasPos = mGasPos * (GAS_Pressure - minPosVolGas) + minInjPerPos;

      mGasNag = (maxInjPerNag - minInjPerNag) / (maxNagVolGas - minNagVolGas);
      yGasNag = mGasNag * (GAS_Pressure - minNagVolGas) + minInjPerNag;

      if(GAS_Pressure >= 0.00 && GAS_Pressure < 2.50)
      {
        gasInjTime = injTime + (injTime * yGasPos);
      }
      else if(GAS_Pressure >= 2.50 && GAS_Pressure <= 5.00)
      {
        gasInjTime = injTime - (injTime * yGasNag);
      }

      //--------------------Pulse Generation-----------------------//

      if((kInjTime > 0) && ((millis() - kInjTime) >= gasInjTime))
      {
        kInjTime = 0;
        digitalWrite(kPinInj, LOW);
      }
    }

    //----------------------------RPM----------------------------//

    void countRPM()
    {
      RPMpulses++;

      kInjTime = millis();
      digitalWrite(kPinInj, HIGH);
    }

    int getRPM()
    {
      Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
      RPMpulses = 0;
      Final_RPM = min(99999, Final_RPM);
      return Final_RPM;
    }
    //-----------------------------------------------------------//

Here, it's my oscilloscope output after suggestion of user Majenko.
Purple one is INPUT Pin 2 Square wave and Yellow one is OUTPUT Pin 13 Square wave.It's perfectly synchronized.
[![Synchronized Waves][1]][1]

Now, I want to see my all readings on serial monitor, so for that, I used `Serial.print()` line. But, now one problem is appeared. Because of this line, my OUTPUT Pin 13 Waveform not synchronized with INPUT Pin 2 Waveform:

Below my code after adding `Serial.print()` in my code to display readings on serial monitor. You can see bunch of lines of `Serial.print()` at the end of the code :

    //----------------------------For MAP calculation----------------------------//
    float MAP_MIN = 0.85;
    float MAP_MAX = 1.90;

    int LOAD_MIN_MAP[] = {2, 10};
    int LOAD_MAX_MAP[] = {15, 85};

    float mMAP[2] = {};
    float yMAP[2] = {};

    int i, j, a;
    float MAP, mFinalMAP, yFinalMAP;

    //----------------------------For TPS calculation----------------------------//
    float TPS_MIN = 0.00;
    float TPS_MAX = 5.00;

    int LOAD_MIN_TPS[] = {2, 15};
    int LOAD_MAX_TPS[] = {10, 85};

    float mTPS[2] = {};
    float yTPS[2] = {};

    int k, l, b;
    float TPS, mFinalTPS, yFinalTPS;

    //----------------------------For LOAD calculation---------------------------//
    int LOAD_MIN = 2;
    int LOAD_MAX = 100;

    float injTime_MIN_LOAD[] = {4.00, 8.06};
    float injTime_MAX_LOAD[] = {4.60, 14.86};

    float mLOAD[2] = {};
    float yLOAD[2] = {};

    int m, n, c;
    float LOAD, mFinalLOAD, yFinalLOAD;

    //----------------------------For RPM calculation----------------------------//
    const int kPinRPM = 3;        // RPM / Digital Pin 3
    const int RPMInterrupt = 1;   // RPM's interrrupt pin
    byte engineCylinders = 2;         // Engine cylinders = 4;
    byte engineCycles = 4;            // Engine cycle = 2
    int refreshInterval = 750;        // Milliseconds between sensor updates
    unsigned long previousMillis = 0;
    volatile int RPMpulses = 0;
    int RPM, Final_RPM;

    int RPM_MIN = 400;
    int RPM_MAX = 6000;

    float injTime_MIN_RPM[] = {4.00, 4.60};
    float injTime_MAX_RPM[] = {8.06, 14.86};

    float mRPM[2] = {};
    float yRPM[2] = {};

    int o, p, d;
    float mFinalRPM, yFinalRPM;

    //------------------------For GAS PRESSURE calculation-----------------------//
    float minPosVolGas = 0.00;
    float maxPosVolGas = 2.50;

    float minInjPerPos = 0.35;
    float maxInjPerPos = 0.00;

    float minNagVolGas = 2.50;
    float maxNagVolGas = 5.00;

    float minInjPerNag = 0.00;
    float maxInjPerNag = 0.25;

    float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

    //----------------------For INJECTION TIME calculation-----------------------//
    float yInjTime, injTime, gasInjTime;
    volatile uint32_t kInjTime = 0;

    const int kPinInj = 13;

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

      pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
      attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

      pinMode(kPinInj, OUTPUT);
    }

    void loop()
    {
      //----------------------------MAP----------------------------//

      MAP = analogRead(A0) * (5.0 / 1023.0);

      for(a = 0; a < 2; a++)
      {
        mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
        yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
      }

      //----------------------------TPS----------------------------//

      TPS = analogRead(A1) * (5.0 / 1023.0);

      for(b = 0; b < 2; b++)
      {
        mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
        yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
      }

      //----------------TPS/MAP CALLIBRATION / LOAD----------------//

      mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
      yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

      mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
      yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

      LOAD = (yFinalTPS + yFinalMAP) / 2;

      //----------------------------LOAD---------------------------//

      for(c = 0; c < 2; c++)
      {
        mLOAD[m] = (injTime_MAX_LOAD[c] - injTime_MIN_LOAD[c]) / (LOAD_MAX - LOAD_MIN);
        yLOAD[n] = mLOAD[m] * (LOAD - LOAD_MIN) + injTime_MIN_LOAD[c];
      }

      //----------------------------RPM----------------------------//

      if(millis() - previousMillis > refreshInterval)
      {
        previousMillis = millis();
        RPM = getRPM();
      }

      for(d = 0; d < 2; d++)
      {
        mRPM[o] = (injTime_MAX_RPM[d] - injTime_MIN_RPM[d]) / (RPM_MAX - RPM_MIN);
        yRPM[p] = mRPM[o] * (RPM - RPM_MIN) + injTime_MIN_RPM[d];
      }

      //-----------LOAD/RPM CALLIBRATION / INJECTION TIME----------//

      mFinalLOAD = (yRPM[1] - yRPM[0]) / (LOAD_MAX - LOAD_MIN);
      yFinalLOAD = mFinalLOAD * (LOAD - LOAD_MIN) + yRPM[0];

      mFinalRPM = (yLOAD[1] - yLOAD[0]) / (RPM_MAX - RPM_MIN);
      yFinalRPM = mFinalRPM * (RPM - RPM_MIN) + yLOAD[0];

      yInjTime = (yFinalLOAD + yFinalRPM) / 2;
      injTime = (yInjTime * 1000) / 1000;

      //------------------------GAS_PRESSURE-----------------------//

      GAS_Pressure =  analogRead(A2) * (5.0 / 1023.0);

      mGasPos = (maxInjPerPos - minInjPerPos) / (maxPosVolGas - minPosVolGas);
      yGasPos = mGasPos * (GAS_Pressure - minPosVolGas) + minInjPerPos;

      mGasNag = (maxInjPerNag - minInjPerNag) / (maxNagVolGas - minNagVolGas);
      yGasNag = mGasNag * (GAS_Pressure - minNagVolGas) + minInjPerNag;

      if(GAS_Pressure >= 0.00 && GAS_Pressure < 2.50)
      {
        gasInjTime = injTime + (injTime * yGasPos);
      }
      else if(GAS_Pressure >= 2.50 && GAS_Pressure <= 5.00)
      {
        gasInjTime = injTime - (injTime * yGasNag);
      }

      //--------------------Pulse Generation-----------------------//

      if((kInjTime > 0) && ((millis() - kInjTime) >= gasInjTime))
      {
        kInjTime = 0;
        digitalWrite(kPinInj, LOW);
      }

      Serial.print("TPS : ");
      Serial.print(TPS);
      Serial.print("\t");
      Serial.print("MAP : ");
      Serial.print(MAP);
      Serial.print("\t");
      Serial.print("LOAD : ");
      Serial.print(LOAD);
      Serial.print("\t");
      Serial.print("RPM : ");
      Serial.print(RPM);
      Serial.print("\t");
      Serial.print("GAS Pressure : ");
      Serial.print(GAS_Pressure);
      Serial.print("\t");
      Serial.print("Injection Time : ");
      Serial.print(gasInjTime);
      Serial.print("\n");
    }

    //----------------------------RPM----------------------------//

    void countRPM()
    {
      RPMpulses++;

      kInjTime = millis();
      digitalWrite(kPinInj, HIGH);
    }

    int getRPM()
    {
      Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
      RPMpulses = 0;
      Final_RPM = min(99999, Final_RPM);
      return Final_RPM;
    }
    //-----------------------------------------------------------//

My oscilloscope output. You can see no synchronization between that waveform. I don't know why this happens. Can I have to switch to ARDUINO MEGA because may be ARDUINO UNO processing speed not able to perform. Give some suggestion :
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/oxyr2.jpg
  [2]: https://i.stack.imgur.com/b7QXe.jpg

body:
Here is how I would do it:

    volatile uint32_t injTime = 0;

    void setup() {
        pinMode(13, OUTPUT);
        pinMode(2, INPUT);
        attachInterrupt(0, countRPM, FALLING);
    }

    void loop() {
        if ((injTime > 0) && ((millis() - injTime) >= 10)) {
            injTime = 0;
            digitalWrite(13, LOW);
        }
    }

    void countRPM() {
        injTime = millis();
        digitalWrite(13, HIGH);
    }

Basically, when the interrupt triggers you remember *when* it triggered and turn on the relay.

Then in your main loop, if the interrupt has been triggered, and 10 milliseconds have elapsed *since* the interrupt was triggered, then forget that the interrupt was triggered (so you can see the next one) then turn the relay off.

The key point is that you remember when the interrupt triggered, and count your time from that point onwards.

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

Blue is input to pin 2. Yellow is output of pin 13.

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


sender: user

message:
How I Can Send the status of switch in SMS by Arduino?

How I want help ,, I want send status of Switch If switch > 20 send SMS status of switch OFF and when switch <20 than mean switch ON , Don't want send the value of reading.
I use Arduino uno

If I want use multiple switch and send all status of switchs in one message.
I mean if switch1 > 20 ON and switch2 <20
I want send status of switch In one SMS
Switch1 ON
Switch2 OFF
Switch3 OFF

How I can do this??

    void loop()
    Switch = analogRead(S_Switch);
    if (Switch > 20 )
    {
    Serial.println(Switch);// If Switch > 20 show in SMS switch statuse  OFF,, If switch < 20 show in SMS switch statuse ON
    Serial.print("\n******************\n");
    Sim900Serial.print("AT+CMGF=1\r"); //Sending the SMS in text mode
    delay(1000);
    Sim900Serial.println("AT + CMGS = \"+***************\"");//The predefined phone number
    delay(1000);
    Sim900Serial.println("MY Swicth statuse is :");
    Sim900Serial.println(Switch); // I don't want the value of Switch I want ( ON , OFF )
     Sim900Serial.print("              ");
    Sim900Serial.println((char)26);//the ASCII code of the ctrl z is 26
    delay(5000);
    Sim900Serial.println();
    }

sender: assistant

body:
Here, Updated Code...

    const int switchOneInput = A0; // Switch 1
    const int switchTwoInput = A1; // Switch 2

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

    void loop()
    {
      int switchOneStatus = analogRead(A0);
      int switchTwoStatus = analogRead(A1);

      // When Switch 1 is OFF and Switch 2 is OFF
      if(switchOneStatus < 20 && switchTwoStatus < 20)
      {
        smsOne();
      }

      // When Switch 1 is ON and Switch 2 is OFF
      else if(switchOneStatus > 20 && switchTwoStatus < 20)
      {
        smsTwo();
      }

      // When Switch 1 is OFF and Switch 2 is ON
      else if(switchOneStatus < 20 && switchTwoStatus > 20)
      {
        smsThree();
      }

      // When Switch 1 is ON and Switch 2 is ON
      else if(switchOneStatus > 20 && switchTwoStatus > 20)
      {
        smsFour();
      }

    }

    void smsOne()
    {
      Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
      Serial.print("\r");
      delay(1000);
      Serial.print("AT+CMGF=1\r");
      delay(1000);
      Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
      delay(1000);
      Serial.print("Switch 1 is OFF and Switch 2 is OFF\r");   //The text of the message to be sent
      delay(1000);
      Serial.write(0x1A);
      delay(1000);
    }

    void smsTwo()
    {
      Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
      Serial.print("\r");
      delay(1000);
      Serial.print("AT+CMGF=1\r");
      delay(1000);
      Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
      delay(1000);
      Serial.print("Switch 1 is ON and Switch 2 is OFF\r");   //The text of the message to be sent
      delay(1000);
      Serial.write(0x1A);
      delay(1000);
    }

    void smsThree()
    {
      Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
      Serial.print("\r");
      delay(1000);
      Serial.print("AT+CMGF=1\r");
      delay(1000);
      Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
      delay(1000);
      Serial.print("Switch 1 is OFF and Switch 2 is ON\r");   //The text of the message to be sent
      delay(1000);
      Serial.write(0x1A);
      delay(1000);
    }

    void smsFour()
    {
      Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
      Serial.print("\r");
      delay(1000);
      Serial.print("AT+CMGF=1\r");
      delay(1000);
      Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
      delay(1000);
      Serial.print("Switch 1 is ON and Switch 2 is ON\r");   //The text of the message to be sent
      delay(1000);
      Serial.write(0x1A);
      delay(1000);
    }


message:
How to vary the frequency of a PWM sinewave with arduino uno?

I'm generating a sine wave using a table, a PWM pin and an RC filter on the output. I would like to be able to control the frequency of the sine wave, how can I do that easily?

By the way, which is the maximum frequency achievable and why? As far as my understanding goes, the limit is given by the time arduino needs in order to run the loop() function.

This is the code I am using on arduino UNO. Please point it out if this is a horrible way to generate a sine wave with arduino, and if it is, feel free to provide a better solution.

    const int8_t SIN1024_DATA [] = {... data table values (1024 values) ...};
    int i = 0;
    void setup()
    {
      pinMode(9, OUTPUT);
    }

    void loop()
    {
      digitalWrite(9, SIN1024_DATA[i]);
      i++;
      if(i == 1024){i = 0;}
    }

body:
First thing, you must find a way to output the samples at a steady rate.
Your best bet is to use a timer. Ideally, you want to use the same timer
used for the PWM output, in order to have them synchronized. See for
example how it is done in the [Mozzi sound synthesis
library](https://sensorium.github.io/Mozzi/).

Then you can lower the frequency by repeatedly outputting the same
value: if you output every value once, you get the “base” frequency
(sample frequency ÷ 1024). If you output each value _n_ times you get
the base frequency divided by _n_. Conversely, you can get higher
frequencies by skipping samples. For example, if you output only every
other sample, you get twice the base frequency.

These two approaches can be conveniently combined in a very simple code:
you keep a `phase` variable and, on every sample, you increment it by an
amount proportional to the desired frequency. You then use the higher
bits of the phase as an index into your array. The lower bits then serve
only to increase the frequency resolution and allow frequencies lower
than the base one. Here is a simple implementation:

    const uint8_t pin = ...;
    uint8_t frequency;

    // Call periodically.
    static inline void output_a_sample()
    {
        static uint16_t phase;
        analogWrite(pin, SIN1024_DATA[phase>>6]);
        phase += frequency;
    }

This lets you set the frequency in units of the sampling frequency ÷
216, i.e. the base frequency ÷ 26.

Note that the phase here is 16-bits: 10 bits for the array index and 6
bits for the fractional part. Since all the bits are used, you do not
need to handle the rollover: a `uint16_t` automatically rolls over
modulo 216, which is just what you want here. You can use a
32-bit variable if you need more frequency resolution.


message:
24LC1025 Arduino - Data Writing Problem

I have a very big problem by writing a list of strings to an eeprom (24LC1025) Your help with my problem highly appericiated.

I have a data matrix, PageData[111][96] and I want to write all them at once, line by line to the eeprom. I am using arduino for coding.

the code is :

    {

    #include <Wire.h>

    #define EEPROM_ADDR 0xA0;

    void setup()
    {

      Wire.begin();

      Serial.begin(9600);
    int PageData[111][96]={ my data is here ... }

     for (t=0; t<111; t++){
      for (unsigned long i=0; i<96; i++){
        m=i*2;
        value[m] = highByte(PageData[t][i]);
        value[m+1] = lowByte(PageData[t][i]);   }

      at=((t*192));

     for (unsigned long i=0; i< 192; i++) {
        i2c_eeprom_write_byte(EEPROM_ADDR,(at+i),value[i]);
        delay(5);                             }
          }

    void i2c_eeprom_write_byte( int deviceaddress, unsigned long eeaddress, byte data )
    {
    if( eeaddress > 65535 )
        deviceaddress = deviceaddress | B00001000;

        deviceaddress = deviceaddress >> 1;

      byte rdata = data;
      Wire.beginTransmission(deviceaddress);
      Wire.write((int)(eeaddress >> 8));    // Address High Byte
      Wire.write((int)(eeaddress & 0xFF));  // Address Low Byte
      Wire.write(rdata);
      Wire.endTransmission();
    }

My problem in this code: when I want to read the eeprom for the checking the strings, I realize, it does not write the eeprom the whole 111 line. It just writes randomly sometimes half of this sometimes less than this amount.

I tried several ways to solve the problem. but now I am desperate , please check this and tell me where i miss a point. Please let me know, if any information you need for the answer.

body:
Writing a single byte is really bad. You are causing a page write with each bye, and each page has a limited lifetime (100,000 - 1,000,000 cycles) so use block instead.

> When writing any amount of data, including a single byte using this
> function,   the EEPROM will refresh the entire page (128 bytes) of
> data.   EEPROMs have a limited write endurance (often 1 million cycles
> per page).   Therefore, if you write one byte at a time, instead of
> writing a full block   at once, you are *wasting the chip's lifetime*
> (doing so is also MUCH slower).   ONLY use this if you really only
> need to write ONE byte, and avoid it   when you can.   Using a block
> write (below), you can write 128 bytes and only use a single   page
> write (or *at most* two, if the write is not aligned to a page
> boundary).

This library should do the trick for you:
https://github.com/exscape/electronics/tree/master/Arduino/Libraries/EEPROM/EEPROM_24XX1025


message:
Simple reading and writing on Floppy Disk

I am trying to interface a 3.5" floppy drive (read and write data onto floppy disc). Since I need to write just few bit long number on it (16 is more than enough) I am thinking I could write it track-wise (each track is one bit), which gives me teoretically 80 bit long number, so I could write 4 times 16 bit long number for some redundancy.

I found [this](https://arduino.stackexchange.com/questions/3702/controlling-floppy-disk-drive-with-arduino) code, which solves reading data out. For writing I found [this](http://quantumnet.wikidot.com/interfacing-a-floppy-drive) page which says, that writing should be similar easy process.

I attached code I am running [here](http://pastebin.com/Bvh4Egiy). Reading seems to work, but writing not. The interesting part of code is:

    void writeData(byte data){
      Serial.println("Writing");
      digitalWrite(writeEnablePin, LOW); //starting spining a motor
      digitalWrite(motorEnableBPin, LOW); //enabling motorEnable
      stepAllTheWayOut(); //moving head to the edge of drive
      for(unsigned i = 0; i<10; i++){ //repeating 10 times
        for(unsigned index = 0; index<=8; index++){ //repeating 8 times (there are 80 tracks)
          digitalWrite(writeDataPin,bitRead(data,index)); //setting data pin
          Serial.print(bitRead(data,index)); //printing out what is being written
          delay(500); //spinning for a while to write all over the track
          digitalWrite(writeEnablePin, HIGH); //stepping not working when writeEnablePin is LOW
          stepIn();
          digitalWrite(writeEnablePin, LOW);
        }
        Serial.println("");
      }
      digitalWrite(motorEnableBPin, HIGH);
      digitalWrite(writeEnablePin, HIGH);
    }

The output is:

    Setup done.
    Writing
    010101010
    010101010
    010101010
    010101010
    010101010
    010101010
    010101010
    010101010
    010101010
    010101010
    Reading
    111001000
    101010001
    110111001
    001000101
    001011001
    111111101
    110101101
    111110011
    111111001
    101111110
The output is not what should be written. (the bits are changed every time i run the code)

Any idea what am I doing wrong when writing?

body:
    for(unsigned index = 0; index<=8; index++)

I think that need to be

    for(unsigned index = 0; index<8; index++)

Otherwise you are trying to read the 9th bit in a byte.


message:
Stop time in Tkinter Stopwatch with a PushButton

So, my main goal is to make a stopwatch with Tkinter, in which time is stoppped with an external pushbutton

My void loop function in Arduino Uno is

    void loop() {

    if(digitalRead(BUTTON) == HIGH){
        Serial.print("E\n");
    digitalWrite(LED, HIGH);

    while(1){

     if(digitalRead(BUTTON) == HIGH){
      continue;
      }

    if(digitalRead(BUTTON) == LOW){
    break;}

            }
                                   }

  }

Basically, whenever the pushbutton is pressed I send via serial the message "E\n" and the arduino enters in an infinte loop that only breaks when the pushbutton stops being pressed (to avoid sending more than one message).

Then I have my Python code that reads the serial through the serial.readline() function.

Part of my Python code is (remember that i'm making a stopwatch and time is appearing in the screen - variable timer[i] is what saves the second and the ms):

    def update_timeText():
        if (state):
           global timer
           # Every time this function is called,
           # it increments 1/100 of a second
           timer[1] += 1

          # Every 100 centisecond is equal to 1 second
           if (timer[1] >= 100):
               timer[1] = 0
               timer[0] += 1

           if arduino.readline() == 'E\n':
               print("FLAG\n")

           # TIME STRING
           timeString = pattern.format(timer[0], timer[1])

           # UPTADE THE LABEL WITH TIME STRING
           timeText.configure(text=timeString)

       # Call the update_timeText() function after 1 centisecond
       root.after(10, update_timeText)

The variable state goes True whenever I start the stopwatch (via a Tkinter button, but that's irrelevant for this case).

My problem, is that the program stops in the line

    if arduino.readline() == 'E\n':

i.e., it only continues if I press the pushbutton. What I think that is happening, is that the .readline() continues waiting and waiting until it receives the message 'E\n'... I've tried with the .readline.strip() and also only .read() but none of them worked.

It is though very strange, because if the condition in front of If is not verified, it should just continue...

Any suggestion?

body:
In the [pyserial docs][1] it states this:

>Be careful when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

You need to specify the timeout and the end of line string. Try using this  modified line:

    if arduino.readline(eol='\n') == 'E\n':
Also, add the timeout option where you define arduino as a pyserial object. For example:

    arduino = pyserial.serial(port,baud,timeout=t,etc...)

  [1]: http://pyserial.readthedocs.io/en/latest/shortintro.html#readline


message:
Reading a 10-byte buffer out of a PROGMEM string stored in a string table

I'm storing a large snippet of text in three separate PROGMEM char arrays:

    const char script1[] PROGMEM = "....";
    const char script2[] PROGMEM = "....";
    const char script3[] PROGMEM = "....";

The first two are 32766 characters, and the last one is 23867 characters (the whole string is 89400 characters in total). I store these in PROGMEM on an Arduino Mega 2560 (which then uses about 90K of 256K of available program memory).

I stored these three strings in a table, together with their lengths:

    const int TABLE_SIZE = 3;
    const char * const scriptTable[] PROGMEM =
    {
      script1,
      script2,
      script3
    };

    const int scriptLengths[] {32767, 32767, 23867};

I have some issues trying to chunk up the string into 10-byte buffers, and processng it that way. I want to iterate through the table, process the first part in 10-byte chunks first, then move on to the second part, and finally the last part.

For a single string (`code`), the following works fine:

    const char code[] PROGMEM = "....";

    // Chunk up large code string in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    int baseIndex = 0;

    while (baseIndex < sizeof(code)) {
        int chunk;
        if (baseIndex + CHUNKSIZE > sizeof(code)) {
            chunk = sizeof(code) - baseIndex;
            }
            else {
              chunk = CHUNKSIZE;
            }
            memcpy_PF(workingSpace, ((uint_farptr_t)code) + baseIndex, chunk);
            workingSpace[chunk] = '\0';

            // for debugging
            Serial.print("#");
            Serial.print(baseIndex);
            Serial.print("– Got a chunk [");
            Serial.print(workingSpace);
            Serial.println("]");

            baseIndex += CHUNKSIZE;

However, I'm having some difficulties doing the memcpy_PF call using the table.

    int tableIndex = 0;
    // for each of the three script strings
    for (tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++) {
        // Chunk up large script strings in PROGMEM.
        const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
        char workingSpace[CHUNKSIZE + 1];
        int baseIndex = 0;

        // we can only use sizeof if it's a static var.
        // strlen should only be calculated once, expensive operation (loop until we encounter '\0').
        // now stored statically in scriptLengths table.
        Serial.println("tableIndex: ");
        Serial.println(tableIndex);
        int strLength = scriptLengths[tableIndex];
        Serial.print("length script string: ");
        Serial.println(strLength);

        while (baseIndex < strLength) {
            int chunk;
            if (baseIndex + CHUNKSIZE > strLength) {
              chunk = strLength - baseIndex;
            }
            else {
              chunk = CHUNKSIZE;
            }
            // do memcpy_PF call here

I have tried several options here, mostly having difficulties with the second parameter (how to address the string stored in the table, and increase its indexing parameter). I read that the way to get a string out of a string table is to use pgm_read_word. However, with both of these below, I either get gibberish in the buffer string, or it seems to start in an incorrect location in the string.

    memcpy_PF(workingSpace, ((uint_farptr_t) &scriptTable[tableIndex][baseIndex]), chunk);
    memcpy_PF(workingSpace, ((uint_farptr_t) (char*)pgm_read_word(&(scriptTable[tableIndex])) + baseIndex), chunk);

Any help would be greatly appreciated!

Thanks!

body:
The first thing you need to fix is this:

    /home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino: In function 'foo()':
    /home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino:42:27: warning: iteration 3276 invokes undefined behavior [-Waggressive-loop-optimizations]
         baseIndex += CHUNKSIZE;

You are adding 10 to 32760 hoping to be >= `sizeof(code)` however now `baseIndex` will become negative as an int goes from -32768 to +32767.

---

There were some interesting subtleties to getting this working. :)

One of your major problems is this:

    const char * const scriptTable[] PROGMEM =

That will give you 2-byte pointers (const char *) which will not be large enough to index into 89400 characters.

So you need to have an array of 4-byte pointers like this:

    uint_farptr_t  scriptTable [TABLE_SIZE] =

However you can't just initialize those like you tried to. That has to be done procedurally with a macro that pulls in the full address. My working code is below:

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

    #include "code.cpp"

    const int TABLE_SIZE = 3;
    uint_farptr_t  scriptTable [TABLE_SIZE];  // values calculated at runtime
    const int scriptLengths[TABLE_SIZE]
      {
      sizeof (script1),
      sizeof (script2),
      sizeof (script3)
      };

    void foo ()
    {
      // for each of the three script strings
      for (byte tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++)
        {
        // Chunk up large script strings in PROGMEM.
        const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
        char workingSpace[CHUNKSIZE + 1];
        long baseIndex = 0;

        Serial.println ("----------------");
        Serial.print("tableIndex: ");
        Serial.println(tableIndex);
        long strLength = scriptLengths[tableIndex];
        Serial.print("length script string: ");
        Serial.println(strLength);

        while (baseIndex < strLength) {
          int chunk;
          if (baseIndex + CHUNKSIZE > strLength) {
            chunk = strLength - baseIndex;
          }
          else {
            chunk = CHUNKSIZE;
          }
          memcpy_PF(workingSpace, scriptTable [tableIndex] + baseIndex, chunk);
          workingSpace[chunk] = '\0';

          // for debugging
          Serial.print("#");
          Serial.print(baseIndex);
          Serial.print("- Got a chunk [");
          Serial.print(workingSpace);
          Serial.println("]");
          delay (50);
          baseIndex += CHUNKSIZE;
        } // end of while
      } // end of for
    } // end of foo

    void setup()
    {
      // get proper pointers to the various pieces of progmem
      scriptTable [0] = pgm_get_far_address (script1);
      scriptTable [1] = pgm_get_far_address (script2);
      scriptTable [2] = pgm_get_far_address (script3);

      Serial.begin (115200);
      foo ();
    }

    void loop()
    {
    }

The file "code.cpp" just has the actual data in it (generated at http://www.lipsum.com).

As in:

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

    #include <Arduino.h>

    const char script1[] PROGMEM =  {

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit.  ... " };

    const char script2[] PROGMEM =  {

    "Aliquam erat volutpat. Praesent aliquet accumsan arcu,  ... " };

    const char script3[] PROGMEM =  {

    "Ut neque dolor, condimentum ut odio iaculis,  ... " };

Output:

    ----------------
    tableIndex: 0
    length script string: 32767
    #0- Got a chunk [Lorem ipsu]
    #10- Got a chunk [m dolor si]
    #20- Got a chunk [t amet, co]
    #30- Got a chunk [nsectetur ]
    #40- Got a chunk [adipiscing]
    #50- Got a chunk [ elit. Pro]
    #60- Got a chunk [in sit ame]
    #70- Got a chunk [t purus cu]
    #80- Got a chunk [rsus, dict]
    #90- Got a chunk [um magna q]
    #100- Got a chunk [uis, place]
    #110- Got a chunk [rat dui. I]
    #120- Got a chunk [nteger ali]

    ...

    #32700- Got a chunk [, eget tem]
    #32710- Got a chunk [por dui te]
    #32720- Got a chunk [mpor a. Do]
    #32730- Got a chunk [nec malesu]
    #32740- Got a chunk [ada mi et ]
    #32750- Got a chunk [dolor cras]
    #32760- Got a chunk [ amet.]
    ----------------
    tableIndex: 1
    length script string: 32767
    #0- Got a chunk [Aliquam er]
    #10- Got a chunk [at volutpa]
    #20- Got a chunk [t. Praesen]
    #30- Got a chunk [t aliquet ]

It successfully transitioned from the first array to the second one.


message:
Aurduino Smart Wifi Wall Socket

i wanted to make a remote controlled wall socket over wifi (and maybe internet in the future) with an Arduino, i'm relatively new to Arduino, i know only the basics of programming. My idea was to use a Arduino Pro Mini, a relay, a Esp8266 wifi module to connect to my home wifi and maybe a module to monitor consumption like the ACS712 current sensor but i don't know how to make all of this work, maybe i can get the Arduino working but i don't know how to control it on the client side like an app or web interface on my phone/computer.

body:
All the Hardware mentioned are correct,

Arduino Pro Mini (Micro-controller) - To control the Relay

5V Trigger Relay(240V) which would be trigger using a digital Pin on the Arduino.
http://www.instructables.com/id/Controlling-AC-light-using-Arduino-with-relay-modu/

Once you accomplish the steps above you must hook up your wifi module.
Then write a software in your preferred/environment for example, Visual Studio C#, and Use the a UDP or Telnet or HTTP Web-Server ( http://blog.nyl.io/esp8266-led-arduino/ ) connection to sends command to the Arduino though the Wifi Shield, which will trigger the Relay and therefore turn on the Switch.

Also you must find an adapter that sits into the socket and convert 240V AC to 5V DC power to match the consumption of your Arduino.


body:
The hardware you have chosen is perfect for the job at hand.
But what @Hapi also mentioned was that you could probably do away by not using the Arduino !
The ESP8266 is in itself programmable. There are many Firmwares available to help you do so. (You can even program your own)

This can help you getting started : http://randomnerdtutorials.com/esp8266-web-server/

This is something like what you need at the end : https://hackaday.io/project/4562-esp8266-wifi-smart-garage-door

One thing to note : ESP8266 works with 3V, while your Relay would require 5V.
Happy hacking my friend.


message:
Store a variable?

I want to have a switch, that when on, will grab an analog number and essentially "freeze" it. Similarly to how STO> works on a TI83. What should I be using? Excuse my lack of technical terms, I'm not sure what to search and therefore do not know what to use. Thank you :)

body:
You could use [EEPROM][1] on the Arduino. For example:

    #include <EEPROM.h>

    int valAddr = 0;

    #define analogPin 0
    #define buttPin 3
    void setup() {
      pinMode(buttPin,INPUT);
    }

    void loop() {
      /***
        Need to divide by 4 because analog inputs range from
        0 to 1023 and each byte of the EEPROM can only hold a
        value from 0 to 255.
      ***/
      if(digitalRead(buttPin)){
         int val = analogRead(analogPin) / 4;
         EEPROM.write(valAddr, val);
         //access this value again by using int newvalue = EEPROM.read(valAddr)*4;

      }
    }
By using EEPROM your value will be stored in non-volatile memory, meaning it will stay in memory even after a power cycle which is similar to how `STO>` works.

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


body:
Only read the analogue pin if the button is pressed.

    #define analogPin 0
    #define buttPin 3

    int analogVal = 0;

    void setup() {
      pinMode(buttPin,INPUT);
    }

    void loop() {
        // You can do stuff here

        // If the button is pressed...
        if (digitalRead(buttPin)
        {
            // ..read the analogue pin
            analogVal = analogRead(analogPin) / 4;
        }

        // You can do stuff here
    }


body:
My recommendation:

 1. Configure an external interrupt on the raising edges of the input where the button/switch is wired. Note that only pins 2 and 3 of Uno are capable of external interrupts.

 2. Write a very simple ISR that just sets to `True` a global `volatile` variable (a flag to signal that the button/switch has been actuated) and does nothing else.

 3. In the `loop()` check if the flag variable has been changed by the interrupt. If that's the case, then:
- Debounce/deglitch the button/switch (optional, but highly recommended).
- Read the analog input of your choice and store its value or do whatever you want to do with it.
- Reset the flag variable to `False` so it can be changed the next time the interrupt is fired.


body:
Here's a simple way of tracking the switch and managing the bit of state you need to manage:

    int analogPin = 0;
    int switchPin = 3;
    int switched = 0; // the last-known state of the switch
    int lastRead = 0; // the last-desired analog sample

    void setup() {
      pinMode(switchPin, INPUT_PULLUP); // connect switch to switchPin+GND w/o resistors
    }

    void loop() {

      if(digitalRead(switchPin)){ // switch on:
        if(!switched){ // switch on, but was unknown
          lastRead = analogRead(analogPin); // the wanted leading-edge value
          switched = 1; // seen it on
        }//end if switch changed?
      }else{ // switch off:
        if(switched) switched = 0;      //  remember that switch is off
        lastRead = analogRead(analogPin); // the latest value
      }

      Serial.println("Value is " + String(lastRead));
      delay(500);
    }


body:
Read the analog input and store it, continuously. If the switch is off, also write the value to the "freeze" value:

    void loop(){
       int value, freeze;

       value = analogRead(ANALOGPIN);
       if( !digitalRead(SWITCHPIN) ){
          freeze = value;   // sw is off, upd freeze value
       }
    }

This doesn't take into account possible bouncing of the switch. That may or may not matter depending on the actual rate of sampling the analog input and what you intend to do with the frozen output, as the switch bouncing will be shorter than human perception but long enough (10s of msec, perhaps) for the MCU to notice and react to changes.


body:
> it will continuously read my analog input.

easy:

1. have the adc in free running mode and in the isr writes the adc value to a buffer.

2. watch the state of the button in an isr. if it changes, save the buffer value to something else.

there are simpler ways of doing it but less real time than that. need to watch out for atomicity if a multi-byte value is involved.


message:
Read value from a file inside SD card

it's possible to read value from a file inside sd card?

I'm trying to start with the sample code

    /*
      SD card read/write

     This example shows how to read and write data to and from an SD card file
     The circuit:
     * SD card attached to SPI bus as follows:
     ** MOSI - pin 11
     ** MISO - pin 12
     ** CLK - pin 13
     ** CS - pin 4

     created   Nov 2010
     by David A. Mellis
     modified 9 Apr 2012
     by Tom Igoe

     This example code is in the public domain.

     */

    #include <SPI.h>
    #include <SD.h>

    File myFile;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.print("Initializing SD card...");

      if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.
      myFile = SD.open("test.txt", FILE_WRITE);

      // if the file opened okay, write to it:
      if (myFile) {
        Serial.print("Writing to test.txt...");
        myFile.println("testing1 1, 2, 3.");
        myFile.println("testing2 1, 2, 3.");
        myFile.println("testing3 1, 2, 3.");
        // close the file:
        myFile.close();
        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }

      // re-open the file for reading:
      myFile = SD.open("test.txt");
      if (myFile) {
        Serial.println("test.txt:");

        // read from the file until there's nothing else in it:
        while (myFile.available()) {
          Serial.write(myFile.read());
        }
        // close the file:
        myFile.close();
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }
    }

    void loop() {
      // nothing happens after setup
    }

but here he read all the contnent of the file, i want to read only testing 3 part . Thank's for help

body:
You have 2 options for doing this, depending on what exactly you want to read and how your file is arranged.

1. Read from the beginning until you find what you want. Throw away (just don't keep) what you don't want.
2. Use the `File::seek(uint32_t)` method to jump to a specific byte in the file and read from there. Only useful if you already know *where* in the file your data is.


body:
i found this solution with use of strcmp:
when i read the file i compare the result str coming from file flux

    /*
     SD card read/write

    This example shows how to read and write data to and from an SD card file
    The circuit:
    * SD card attached to SPI bus as follows:
    ** MOSI - pin 11
    ** MISO - pin 12
    ** CLK - pin 13
    ** CS - pin 4

    created   Nov 2010
    by David A. Mellis
    modified 9 Apr 2012
    by Tom Igoe

    This example code is in the public domain.

    */

    #include <SD.h>

    File myFile;
    char buf[10];

    void setup()
    {
    // Open serial communications and wait for port to open:
     Serial.begin(9600);
      while (!Serial) {
       ; // wait for serial port to connect. Needed for Leonardo only
     }

     Serial.print("Initializing SD card...");
     // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
     // Note that even if it's not used as the CS pin, the hardware SS pin
     // (10 on most Arduino boards, 53 on the Mega) must be left as an output
     // or the SD library functions will not work.
      pinMode(10, OUTPUT);

     if (!SD.begin(53)) {
       Serial.println("initialization failed!");
       return;
     }
     Serial.println("initialization done.");

     // re-open the file for reading:
     myFile = SD.open("test.txt");
     if (myFile) {
       Serial.println("test.txt:");

       // read from the file until there's nothing else in it:
       while (myFile.available()) {
          myFile.read(buf,2);
           if(strncmp(buf, "12", 2) == 0)//for lenght i use 2 becouse im looking for a number with 2 digit
           {
               Serial.println("Match!");
               }
              break;
           }
       }
       // close the file:
       myFile.close();
     } else {
      // if the file didn't open, print an error:
       Serial.println("error opening test.txt");
     }
    }

    void loop()
    {
      // nothing happens after setup
    }


message:
Run Code Based on Time From GSM Module (SIM900)

I am trying to check the time from the GSM module to let my code run or do nothing.

If I send the command, AT+CCLK? to the SIM900. This is the response:

    AT+CCLK?

    +CCLK: "17/02/14,16:58:25-20"

    OK

How do I parse the time information from the SIM900 and setup a loop for my code to run if it is past 6pm but before 6am?

My code currently:

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(7,8); //RX,TX

    void setup() {
      PowerOn(); //power on GSM Module
      delay(10000); //delay 10 seconds
      SIM900.begin(19200); //software serial for GSM Shield
      delay(500);
    }

    void loop() {

    // if time is past 6pm and before 6am send text message else do nothing

    SendTextMessage();

    }

    ///GetTime
    void GetTime()
    {
        SIM900.print("AT+CCLK?");
    }

    ///SendTextMessage
    void SendTextMessage()
    {
        SIM900.print("AT+CMGF=1\r");//Because we want to send the SMS in text mode
        delay(100);
        SIM900.println("AT + CMGS = \"+12137777777\"");//send sms message, be careful need to add a country code before the cellphone number
        delay(100);
        SIM900.println("Motion Detected!");//the content of the message
        delay(100);
        SIM900.println((char)26);//the ASCII code of the ctrl+z is 26
        delay(100);
        SIM900.println();
    }

    ///PowerOn
    void PowerOn()
    {
      ///software equivalent of pressing the GSM shield "power" button
      digitalWrite(9, HIGH);
      delay(1000);
      digitalWrite(9, LOW);
      delay(7000);
    }

body:
I'm imagining `SIM900` is a serial stream that supports input methods [`available()`](https://www.arduino.cc/en/serial/available) and [`read()`](https://www.arduino.cc/en/Serial/read).  The hour portion of the response string is a two-digit integer delimited by a comma and a colon.  The following snippets of code assume you trigger a response and then start a [`listen()`](https://www.arduino.cc/en/Reference/SoftwareSerialListen) to connect to the software serial input.  Since `listen()` discards old data, presumably a message like `+CCLK: "17/02/14,16:58:25-20"` will be the next data to arrive.

This code converts any string of digits that it sees into a number.  Whenever it sees a non-digit character, it treats it as a delimiter.

When the previous and current delimiters are ',' and ':', it checks if the current number value is in the desired time range, and if so, it sets a flag, else clears a flag.

When the previous and current delimiters are '-' and '"', it assumes it is done with the parse.  Or one could, possibly, end the parse as soon as the hour field has been processed.

    void loop() {
      // ...
      // somewhere within loop()
      byte num, dell;  // Currrent number and left delimiter
      byte timeFlag, readMore, foundTime;
      //...

      // Send string to elicit +CCLK and tell parser to handle response
      SIM900.listen();  // Discard old input
      SIM900.write("AT+CCLK?"); // Elicit new input
      readMore = true;
      timeFlag = foundTime = false;
      num = 0;
      dell = 0;
      // Read and parse +CCLK input; set or clear timeFlag
      while (readMore) {
        while (!SIM900.available()) {}; // Wait for a character
        char c = SIM900.read();
        if (c >= '0' && c <= '9') { // Is c a digit?
          num = 10*num + c-'0'; // Yes, add it to num
        } else {   // Not a digit, so check for Hour field or End of parse
          if (dell=='-' && c == '"') {
            readMore = false;
          } else
            if (dell==',' && c == ':') {
              timeFlag = (num < 6) || (num >= 18);
              foundTime = true;
            }
          dell = c;         // Record left delimiter of next number
          num = 0;         // Get ready to evaluate next number
        }
      }
      // If foundTime, then timeFlag is true for time in 6 PM to 6 AM, else false
      // ...
      // etc
    }


message:
How to power my Arduino mini using wall socket?

I am trying to power my Arduino Mini (which is connected to IR receiver and a relay board). The idea is to hide the entire setup behind the electrical board including the power supply. I have hacked more than a few power adapters (ranging from Mobile chargers 5-7V to 12 V adapters)

This is what I understand from what I have **read** so far about Arduino Mini power supply.

 1. I can power directly using Vcc pin if I supply 5V DC regulated. (not recommended)

 2. I can power Raw pin by using 5-12V DC and the onboard regulator will take care of converting it. 12V is the maximum, I should not use 12V it can fry the regular if used for a long period as the on-board regulator is a linear one, so a lot of heat.

This is what I understand from what I have **tried** so far about Arduino Mini power supply:

 1. Don't connect power supply EVER to Vcc, it will harm the board. ALWAYS use Raw.
 2. 12 V supply = puff. instantaneously. No more on-board regulator. Now that Arduino Mini only works if I connect it using Vcc. (the charger was rated 12V 500mA)
 3. Connecting 5V DC (300mA) is heating the regulator alot.

I have connected the Relay and IR receiver directly to the Arduino mini. Pin 10-14 are used for the relays Ins and PWD 3 for IR output.

The mini works with these 5V mobile chargers but the amount it ***heats up*** scares me.  Any suggestions on what I should do?

Also how much current consumption would be needed. I have tried using a 5V 300mA charger and 5V 700mA charger. Both work almost the same. Why?

I am a computer engineer and very new to Arduino.

Linking a similar question: https://arduino.stackexchange.com/questions/815/most-compact-method-of-powering-arduino-from-wall-socket

body:
The Arduino website says you should not power your Arduino Mini with more than 9 volts.

> Warning: Don't power the Arduino mini with more than 9 volts, or plug
> the power in backwards: you'll probably kill it.

https://www.arduino.cc/en/Main/arduinoBoardMini

The 5 to 12 Volts (not more than 12V for long time periods) refers to the Arduino UNO and probably others.


body:
1. You certainly can connect a 5v or 3.3v to the Vcc pin for most boards. Most regulators can take a reverse voltage. To be sure, check the data sheet or place a reverse diode on the regulator.

2. Again, depending on the particular regulator your board has. Most of them are good for 16 to 18v. But that can change drastly if more load current is involved.

3. Well, that's your answer then. Put a reverse diode across the regulator, Between the Vcc and raw pins.


body:
> I have connected the Relay and IR receiver directly to the Arduino
> mini. Pin 10-14 are used for the relays Ins and PWD 3 for IR output.

I hope you don't mean that you have connected the coils of the relays directly to the Arduino pins. If that's the case, the surprise won't be the regulator blowing up, but the MCU surviving. Please edit the post and add complete schematics and/or photos of your prototype.

> The mini works with these 5V mobile chargers but the amount it heats
> up scares me. Any suggestions on what I should do.?

Use a small heatsink if you're concerned about the regulator heating up. But it really shouldn't be a problem unless you're driving too much current from it. Have you actually measured the temperature it reaches?

Also, don't feed the coil through the regulator, but directly from the 5V adapter (presuming your relays are 5V). This will save a lot of dissipation in the regulator. NOTE: don't do this if you use a higher (> 5) voltage adapter!!

> Also how much current consumption would be needed. I have tried using
> a 5V 300mA charger and 5V 700mA charger. Both work almost the same.
> Why?

Those current ratings are maximum values, not constant values. So, if your circuit draws let's say 290 mA, both adapters will be able to do the job.

**EDIT:** additional information

To safely and properly use relays with arduino, you need some interfacing electronics like this:

[![MOSFET-controlled relay][1]][1]

Full article from the source, [here][2]. Flyback diode: 1N4148. You can use almost any "logic-level" N-channel MOSFET.

If you're using instead a relay module similar to the shown below, all the required interfacing electronics are already built into it and your digital pins won't suffer any overcurrent condition.

[![Commercial relay module][3]][3]

However, the regulator will (probably) still suffer from excessive current through it. In some of these relay modules you can optionally use a different power line (JD-VCC, see below) for the relay coil. If you own one of these, feed it directly from the 5V adapter, skipping the regulator.

[![Sample schematic for a real module channel][4]][4]

If the relay module doesn't have a separate power line, it may still work when connected to the 5V adapter if the dropout in the regulator is not too big (i.e., the "high" level from the digital pins is not too far away from the adapter voltage).

  [1]: https://i.stack.imgur.com/Gc1Jk.gif
  [2]: http://www.electronics-tutorials.ws/blog/relay-switch-circuit.html
  [3]: https://i.stack.imgur.com/uaEfG.jpg
  [4]: https://i.stack.imgur.com/B41SK.jpg


message:
How to make a servo sweep from 0 to 180 on press of a button on PS2 controller? (without delay)

I am working on a project that requires the servo to make a complete sweep once on pressing a button say r2 on the pS2 controller. I am using the Arduino Mega 2560,a PS2 controller clone, Bill porter's Ps2x library.

I have figured out a way to do so by adding a delay to the code but when the delay is used I can't use other parts of my project. What should I do?

    int pos = 0;    // variable to store the servo position
    int button = 2;  // The button will be on Pin 7
    void setup()
    {
    myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    pinMode(pos, OUTPUT);
    pinMode(button, INPUT);
    digitalWrite (button, LOW);
    }

    void loop()
    {
    if(ps2x.ButtonPressed(PSB_RED))

    for(pos = 0; pos < 90; pos += 90)  // goes from 0 degrees to 90 degrees
    {                                  // in steps of  degree
     myservo.write(pos);

    }
      if(ps2x.ButtonReleased(PSB_RED))

     for(pos = 90; pos>=90; pos-=90)
     {
    myservo.write(pos);
    delay(50);                             // waits 50ms for the servo to reach the position

body: If you already have the code, if you have a good understanding of how it works it shouldn't be too difficult to implement, but you would multitasking it by creating several objects that use a central time value. It should all be here, if you follow them and read them they can explain better than I: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview


message:
How to find integer inside a file with STRNCMP

I'm trying to compare the int number 18 with strcmp but give to me wrong result, the program looking for char 18 and not for integer 18, how i can look for an integer with strcmp?

    /*
     SD card read/write

    This example shows how to read and write data to and from an SD card file
    The circuit:
    * SD card attached to SPI bus as follows:
    ** MOSI - pin 11
    ** MISO - pin 12
    ** CLK - pin 13
    ** CS - pin 4

    created   Nov 2010
    by David A. Mellis
    modified 9 Apr 2012
    by Tom Igoe

    This example code is in the public domain.

    */

    #include <SD.h>

    File myFile;
    char buf[10];

    char bufStringa[24];

    void setup()
    {
    // Open serial communications and wait for port to open:
     Serial.begin(9600);
      while (!Serial) {
       ; // wait for serial port to connect. Needed for Leonardo only
     }

     Serial.print("Initializing SD card...");
     // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
     // Note that even if it's not used as the CS pin, the hardware SS pin
     // (10 on most Arduino boards, 53 on the Mega) must be left as an output
     // or the SD library functions will not work.
      pinMode(10, OUTPUT);

     if (!SD.begin(53)) {
       Serial.println("initialization failed!");
       return;
     }
     Serial.println("initialization done.");

     // re-open the file for reading:
     myFile = SD.open("test.txt");
     if (myFile) {
       Serial.println("test.txt:");

       // read from the file until there's nothing else in it:
       int id=18;
       while (myFile.available()) {
          myFile.read(buf,2);
           if(strncmp(buf, id, 2) == 0) // i think the system give to me te char 18 and not the number 18 how to do this?
           {
               Serial.println("Match!");
               for(int i=0;i<10;i++)
               {
                Serial.print(buf[i]);

               }
                myFile.read(bufStringa, 24);
                for(int i=0;i<24;i++)
               {
                Serial.print(bufStringa[i]);

               }
              break;
           }
       }
       // close the file:
       myFile.close();
     } else {
      // if the file didn't open, print an error:
       Serial.println("error opening test.txt");
     }
    }

    void loop()
    {
      // nothing happens after setup
    }

body:
Maybe make it as:

    char id[] = "18";

This is if you want to find "18" in your file. That's what I understood from your question.

EDIT: I guess you want this http://playground.arduino.cc/Code/PrintingNumbers:

    int num = 18;
    char buffer[100]; // this will hold your number
    itoa(num, buffer, 10);

Function description [here](http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaa571de9e773dde59b0550a5ca4bd2f00). Also it's not to hard to make this your self for integers and it's a good exercise.


message:
how can i generate square pulse at 50khz frequency to drive two mosfets at a duty ratio .6

I have to switch 2 MOSFET IRF640 at a duty ratio of .6 and the frequency of  switching is  50khz how can I generate it with a single aurdino

body:
Lots of ways.

1. Use a timer interrupt.

2. Use a pwm module.

3. Use the output compare module.

4. Use the SPI module.

5. Use a timer.

6. Use a pwm generator.

.......

Literally endless ways of doing it.


body:
This could be achieved either with software (with a timer interrupt or
by polling `micros()`) or with hardware. The software methods, however,
are prone to a high level of jitter. If you want to have a steady
signal, you should use a hardware solution.

The most straightforward hardware option is to use a timer in PWM mode.
I would avoid fiddling with timer 0, as it is used by the Arduino
timekeeping functions. You are left with either timer 1 or timer 2. The
following program configures timer 2 to output the desired signal:

* period = 20 µs = 5 × 64 CPU cycles
* signal HIGH for 12 µs = 3 × 64 CPU cycles.

The output goes to pin 3, which is one of the two PWM pins controlled by
timer 2.

    void setup()
    {
        DDRD |= _BV(PD3);     // OC2B = PD3 = digital 3 as output
        OCR2A  = 5 - 1;       // period = 5 * 64 CPU cycles
        OCR2B  = 3 - 1;       // HIGH for 3 * 64 CPU cycles
        TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
               | _BV(WGM20)   // fast PWM, TOP = OCR2A
               | _BV(WGM21);  // ...ditto
        TCCR2B = _BV(WGM22)   // ...ditto
               | _BV(CS22);   // clock at F_CPU / 64
    }

    void loop(){}

For some in depth information on how timers work, see
[Nick Gammon's tutorial on timers](http://www.gammon.com.au/timers).


message:
Undefined reference in Eclipse of .h and .cpp files

I'm trying to create a linked list for use on the Arduino, in the Eclipse IDE with the Arduino/Sloeber plugin. The linked list is written in a `.h` and `.cpp` file, and included locally in the project.

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

However, when building, I get the error `undefined reference to Structures::LinkedList<int>::LinkedList()`.

And despite the fact that I've added the local folder to the list of includes (and it can find the top level file containing `setup()` and `loop()`), the problem persists;

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

My relevant file listings are below. Any ideas of what settings I can add to Eclipse in order to solve this? Potentially, could it be something to do with the use of `template<typename T>` in the header file?

Thanks very much,

David

FYI: This problem does not occur with the core libraries i.e. I can run examples like Serial and Blink.

My top level `.cpp` is pretty simple:

    #include "LinkedList.h"
    #include "RAStarSearch.h"
    #include "Arduino.h"

    using namespace Structures;
    void setup() { }

    void loop() {
      LinkedList<int> list = LinkedList<int>();
      return;
    }

And the referenced `.h` is:

    #ifndef LINKEDLIST_H_
    #define LINKEDLIST_H_
    #include "Arduino.h"

    namespace Structures {
    template<typename T>
    class LinkedList {
      public:
        /// Struct inside the class LinkedList
        struct Link {
          T value;
          Link *next;
        };

        LinkedList<T>(); ///< Default constructor
        void addValue(T val); ///< prepends new value at beginning of list
        T popValue(); ///< returns first element and deletes Link.
        Link* peekLink(); ///< Looks at first value
      private:
        Link *head; // this is the private member variable. It is just a pointer to the first Node
    };
    const int ERRNUM = 0x8000000; ///<Error number used, as exceptions not supported
    }
    #endif /* LINKEDLIST_H_ */

__EDIT__

On request I have included my code for `LinkedList.cpp`

    #include "LinkedList.h"
    #include "Arduino.h"

    namespace Structures {
      template<typename T>
      LinkedList<T>::LinkedList() {
        head = NULL; // set head to NULL
      }
      template<typename T>
      void LinkedList<T>::addValue(T val) {
        Link *n = new Link();   // create new Node
        n->value = val;             // set value]

        if (head == NULL) { //i.e. if list is empty
          n->next = head;         // make the node point to the next node or NULL
          head = n;    // last but not least, make the head point at the new node.
        } else {
          Link *it = head;
          Link *oldIt = NULL;
          //TODO check edge cases i.e. insertion at beginning and end of list
          while (n->value > it->value){ //until place in list is found, needs T to have > operator
            oldIt = it;
            it = it->next;
          }
          oldIt->next = n; //Set pointer to n
          n->next = it; //Set n pointer to next
        }
      }
      template<typename T>
      T LinkedList<T>::popValue() {
        T retval = ERRNUM;
        if (head != NULL) {
          Link *n = head;
          retval = head->value;
          head = head->next;
          delete n;
        }
        return retval;
      }
      template<typename T>
      typename LinkedList<T>::Link* LinkedList<T>::peekLink() {
        return head;
      }
    }

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

body:
Have you tried placing the H file in the same folder as you main cpp file.  This should prove beyond all doubt that there is nothing wrong with the code (I can't see anything wrong).

I suspect its a path issue.  You need to check that Eclipse is setup up properly to source the libraries from you custom location.  Also it needs to be passing this location on to the compiler.  I don't know how to do that in Eclipse but Google should point you in the right direction. Try this http://forum.arduino.cc/index.php?topic=39972.0 ?

Also you might find it easier to specify the include files in the order system, 3rd party libraries, local libraries and then local include files.  This means that duplicate definition faults are reported against the files nearest to the ones you have written.  If you define time_t using your ordering the fault will be reported against <time.h> rather than your header file.

Also a `using namespace foo` statement removes the benefits that namespaces provide, so its best not to do it.

EDIT
Doh - I should have spotted this sooner.  Template classes have to have the functions inline not in a CPP file.  This is because the CPP file can't change what T is at compile time, but because the H file is included in the file it is used in when it is preprocessed the object represented by T can change.
Basically inline your functions and it will work.


body:
The error you get is telling you that you have not implemented the method.

    LinkedList<T>()

which you use in loop()

In other words: the header file is found and the correct references are made but when the linker tries to pack everything together he finds that he doesn't have an implementation.

The implementation is in LinkedList.cpp in your project but with templates this is not enough.You need to somehow explain the "toolchain" that your project needs a "instantiation of the template" of type int.

The fact you need to specify this is a "limitation" of the toolchain processong of templates and is well documented here https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl.
The same link contains solutions.
The article states "This solution may (or may not!) cause significant code bloat" which is probably one of the reasons why template classes are not so popular in embedded development.
In your case I would simply include LinkedList.cpp in my .ino file and rename the .ino to .cpp.
As I do not have the source code I can not tell you whether this will work.

note that including the LinkedList.cpp in the .ino doesn work because the LinkedList.cpp is included 2 times and there are no include gards in the LinkedList.cpp file


message:
Problem using IRremote library

I am using arduino pro micro 5v 16Mhz. I have built a simple IR transmitter circuit as shown. [![Led is connected to pin 9 through 330ohm resistor][1]][1]

The code i am using is
https://github.com/z3t0/Arduino-IRremote/blob/master/examples/IRsendDemo/IRsendDemo.ino

Although this worked yesterday, it doesn't seem to work now. I was able to turn on and off my TV yesterday but the led is not even blinking now. I checked led, its working.

After hours of trying to make it work I tried different library.
https://github.com/cyborg5/IRLib2/blob/master/IRLib2/examples/send/send.ino

Surprisingly this seems to work but the code is a bit complicated for receiver.

I want to use the first library. Any help is appreciated. Thank you.

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

body: The problem was with timer timer settings in library. I checked different timer configurations with different pins and its working now. I found out that timer4 uses pin 13 which is not used in Pro Micro board so I am now using timer 3.


message:
Where is PORTB defined?

On Arduino I can set digital pins by setting special variables PORTB and PORTD (or maybe they are not variables?). Where are those variables defined? I grepped /usr/share/arduino, but found nothing.

    grep -r 'PORTB' /usr/share/arduino/

body:
PORTB is defined by the "toolchain". It is not defined by Arduino.
For instance in my setup the Arduino Uno uses "toolchain" avr-gcc\4.9.2-amtel3.5.3-arduino2\avr.

If you grep that folder (location dependent on tool and installation options) you will find a file called `iom328p.h` that defines

    #define PORTB _SFR_IO8(0x05)

This is a mapping to a physical address of the cpu.


message:
Problem burning bootloader on ATmega328P using internal clock

I'm trying to burn the arduino bootloader onto my ATmega328P so it uses the internal clock. I followed the tutorial in this [page][1] but I'm getting this error.

    avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Error while burning bootloader.
    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

    avrdude done.  Thank you.

I tried placing a cap from reset to ground but it doesn't wort either.
Any idea on what might be wrong with my procedure?

Thanks

**[EDIT]**

 - I followed the procedure described at the bottom of the page linked (Minimal Circuit (Eliminating the External Clock)).
 - I used the bootloader in "breadboard-1-6-x.zip"
 - I am using the Arduino IDE v1.8.1

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

body: If your ATMEGA328P has already been used with a crystal or already has a bootloader on it, then the fuses will be set to expect a crystal oscillator. In this case, you must initially have a crystal & the associated 2 capacitors connected. Once you have succeeded in burning the bootloader (this process also sets the fuses) you can dispense with the crystal.


body:
As noted in 6v6gt's answer, if the ATmega328 has been set to use a crystal, thereafter a crystal (or an external oscillator) are required for programming, until the fuses have been set to use the internal RC oscillator.  Here are a few thoughts, unfortunately somewhat scattered, on the matter.

If you have a parallel programmer (that delivers high voltage to the Reset pin and uses 8-bit parallel data signalling) you can use it to reset the fuses, since with that programming mode the clock is irrelevant.

Also, [USBasp programmers](http://www.fischl.de/usbasp/) interact with Avrdude to generate a programming clock of some specified frequency,   100kHz by default, 8kHz with the “Slow Clock” jumper installed.  Also see § “Set the clock in software” within [USBasp ICSP programmer quickstart guide](http://www.freetronics.com.au/pages/usbasp-icsp-programmer-quickstart-guide) at freetronics.com.au.  Unlike the Avrdude man page, that reference says the default programming frequency is 375kHz and says “Avrdude’s -B option allows you to set the programming clock speed from software”, while the man page says -B specifies bit clock period (in microseconds) for the JTAG interface or the ISP clock of the JTAG ICE only.  Anyhow, a USBasp can reprogram fuses away from the crystal setting if a crystal or external oscillator is used, without depending on serial port data rates.  I don't know for certain whether it will work without a crystal or oscillator.

Note, rather than “sharing” a crystal via wires from one board to another – a practice that will broadcast lots of RF noise and might not get the signal across anyway – you could instead write a program on one Arduino to toggle a pin at high frequency, and use that output as an external oscillator to drive one of the crystal pins on another chip.  For example, the program below *should* generate a 2.67 MHz square wave on pin PB0 of an Uno or a Nano.

    void setup() {
      cli();    // Avoid timer interrupts
      pinMode (8, OUTPUT); // PB0 is pin 8 on Uno / Nano
      while (1) PINB = 1;
    }
    void loop() {}

In the ATmega328 data sheet, see §14.3.1, Alternate Functions of Port B, and Table 14-3, which lists PB7 as XTAL2 (Chip Clock Oscillator pin 2), and PB6 as XTAL1 (Chip Clock Oscillator pin 1 or External clock input), indicating external oscillator attaches to the PB6 pin.


message:
Send commands to ESP8266 over WiFi

I want to send commands to ESP8266 over WiFi from my phone(I'm working on building an App using PhoneGap). I'm new to this module and WiFi. What I'm doing right now is that I communicate with the module by sending GET (or POST) commands. I'm sure there should be a better way but I can't seem to find how. What is the correct way to talk to ESP8266 over WiFi?

body:
Depending on what best suits your needs, you could use:

 - http GET/POST commands
 - Websockets over http
 - MQTT protocol
 - Your own TCP or UDP socket protocol
 - etc.

In all cases, what you code into the ESP8266 processor/flash will need to receive and process the commands. The possibilities are near endless, since you are writing the App and the code for the module and can make those design decisions.


message:
autoCalibrateAccelerometerOffset() Why does my Z values swing from 0 to 1g in static condition?

I tried to implement the [`autoCalibrateAccelerometerOffset()`][1] function, through the code below on Arduino Genuino 101.

In a static test, without any stress or noise, I read the three axis value.

When I see the data on the serial monitor or on my file created with processing, the Z acceleration values changes from 1~0,99 to 0,00 g.

[![][2]][2]

I think there is an error in my code.

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

    #include "SoftwareSerial.h"
    #include "CurieIMU.h"

    float sensorVals[] = {0,0,0};

    void setup() {

        Serial.begin(9600);
        while (!Serial);

        Serial.println("Inizializzazione del device...");
        CurieIMU.begin();

        CurieIMU.setAccelerometerRange(2);
        CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS,0);
        CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS,0);
        CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS,1);
    }

    void loop() {

        sensorVals[0] = CurieIMU.readAccelerometerScaled(0);
        sensorVals[1] = CurieIMU.readAccelerometerScaled(1);
        sensorVals[2] = CurieIMU.readAccelerometerScaled(2);

        Serial.print(sensorVals[0]);
        Serial.print(",");
        Serial.print(sensorVals[1]);
        Serial.print(",");
        Serial.println(sensorVals[2]);
        delay(100);
    }

  [1]: https://www.arduino.cc/en/Reference/CurieIMUautoCalibrateAccelerometerOffset
  [2]: https://i.stack.imgur.com/MtB97.png

body:
Assuming you aren't jumping up and down while this is happening then it could be:

 - A loose wire
 - A dodgy power supply
 - A bad earth connection
 - A fault sensor
 - A weird magnetic field/flux thing

Check you wiring, make sure all the connections are secure, etc.  I bet you have done that already.

I have no idea how to check a power supply, but if you have a different one you could switch that in.  Also look into smoothing the power supply with decoupling capacitors (?)

A bad earth, all sorts of weird [stuff] happens when you haven't earthed things properly.  Different power supplies need to share earths, but I suspect that doesn't apply here.

A faulty sensor - again, unless you have a duplicate you might not know.

Weird flux.  I think the sensor is a magnetic sensor and so it could be the natural eddies and flows of magnetic flux have conspired against you.  Move the sensor away from power supplies, electrical things and specifically anything you are hacking.  Also rotate the sensor through 90 degrees and see if it still happens (With RF it will polarise the fields in a different way, and school was a long time ago and I can't remember if that works with magnetic fields too)


message:
How to set counter for two ultrasonic sensors?

This question has been asked many times in many sites but I am unable to find answer for my problem. I wanted to measure the speed of Vehicle using Ultrasonic sensors. Two sensors are placed along the side of the road and when a vehicle passes in front of first sensor(i.e echo1 is HIGH) then it should start counting until when the vehicle crosses the second sensor(i.e echo2=HIGH). So I will get the time. But I don't know how to set time counter. I searched in Internet a lot and I learnt about millis(). So I wrote code using millis(). But the problem is,it starts counting as the program runs. I also tried using array to save the values and subtract final reading from initial one but I'm unable to do that too. I cannot create large size of arrays. Please help me how do I set timer for it?

body:
Just get the time when the first pin goes high, and get it again when the second pin goes high, and subtract them to find the difference.

This is an example of how you could do that. It doesn't contain anything about the ultrasonic sensors, just how to measure an elapsed time between two pins going high.

    #define echo1 3 // Set your echo pins here
    #define echo2 4

    unsigned long startTime = 0;
    unsigned long endTime = 0;

    void setup() {
    }

    void loop() {
        // You can do stuff here

        // If the first sensor goes off
        if (digitalRead(echo1) && (0==startTime))
        {
            // Remember the time this happened
            startTime = millis();
        }
        // If the second sensor goes off
        if (digitalRead(echo2) && (0==endTime))
        {
            // Remember the time this happened
            endTime = millis();
        }

        // If we have both start and end times
        if (0 != startTime && 0 != endTime)
        {
            unsigned long duration = endTime - startTime;
            // Do what you want with "duration"
        }

    }


message:
Is the DHT.h library compatible with ESP8266 Arduino IDE compiler?

I'm using the following 'compiler' to program my ESP8266-01 direct with Arduino IDE:

https://github.com/esp8266/Arduino

and I'm trying to read the temperature and humidity with the following library:

https://github.com/adafruit/DHT-sensor-library

since the DHT library was developed to be used on an Arduino board, should I be able to run it on the ESP8266?

body: As far as I see, the DHT sensor library does bit-banging, which is kind of expected given the ad-hoc nature of the protocol that DHT type of sensors utilize. It should be compatible, as the library doesn't use any Atmel-specific features of the MCU.


body: Yes, it does work. You may have a look at http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html where a list of libraries running with ESP8266 can be found. Furthermore, @anrieff's remarks regarding hardware-specific features are a good hint.