# Question
Title: 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.

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 :

# Answer
> 2 votes
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.

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

---
Tags: arduino-uno, programming, arduino-ide, relay, isr
---


# Question
Title: 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 code, which solves reading data out. For writing I found this page which says, that writing should be similar easy process.

I attached code I am running here. 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?

# Answer
> 2 votes
```
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.

---
Tags: pins, hardware
---


# Question
Title: 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;}
}

```

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

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

---
Tags: arduino-uno, pwm, signal-processing
---


# Question
Title: 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!

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

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

```
#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.
> 2 votes

---
Tags: string, progmem, memory
---


# Question
Title: 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?

# Answer
In the pyserial docs 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...)

```
> 0 votes

---
Tags: serial, button, python
---


title: XBee unstable sensor data transmission

text:
# Question
Title: XBee unstable sensor data transmission
I am using two XBee Series 2 modules (Zigbee), an Arduino Uno, and a HC-SR04 Ultrasonic sensor to send distance readings from the coordinator XBee on the Arduino to the XBee connected to my computer. I configured the ArduinoXBee as "Zigbee coordinator AT" and the ComputerXBee as "Zigbee end device AT" with the following networking settings:

Coordinator: PanID: 1234 DH: 0 DL: FFFF

End Device: PanID: 1234 DH: 0 DL: 0 (so it can only talk to the coordinator)

The problem I am facing is that when I open the End Device terminal on X-CTU, the distance readings I get are accurate yet very unstable. Like it receives the correct readings but the transmission is unsynchronized as it sometimes receives 5 numbers in one transmission and lags for 10 seconds then receives the next bunch and lags for another 10 seconds and so on...

The arduino code is:

```
#include <SoftwareSerial.h>
const int trigPin = 13;
const int echoPin = 9;

SoftwareSerial xbee(10, 11); // RX, TX

void setup()  {
   xbee.begin( 9600 );
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
}
void loop()  {
long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  xbee.println( distance );
  delay(500);
}

```

Can anyone help me?

# Answer
> 1 votes
Probably the end device is set into sleep mode. Check the Sleep Mode(SM) and the sleep period(SP) because what I can see is the XBee gives readings for every 10 seconds.

---
Tags: serial, sensors, xbee
---


# Question
Title: How to transmit characters or just use xbee like serial monitor
I have an arduino mega and an uno, mega has an xbee s2c as coordinator and uno an xbee s2c as router, both in AT ( transparent ) mode. When I send integers from uno with Serial.write() coordinator receives just fine, but when i try float, negative numbers and chars, i get still integers but as I found out sending chars it is in ASCII. I tried Serial.print() but no result. Is there a way to send a negative float from one xbee to the other in AT mode?

Coordinator code

```
void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial1.begin(9600);
  Serial.println("Comersing test!");
}

void loop() {
  if(Serial1.available()>0){
         Serial.print(Serial1.read());
    }
}`

```

UNO code

```
#include <SoftwareSerial.h>
 SoftwareSerial xbSerial(8, 7); // RX, TX
void setup() {
  xbSerial.begin(9600);
  xbSerial.write("First data sent!");

}
int x=4;
void loop() {
  // put your main code here, to run repeatedly:
      xbSerial.write(x);
      x++;
      delay(1000);
      delay(1000);
      delay(1000);
}

```

if I change x in Uno to float, negative or char, I get weird values.

# Answer
XBee cannot send negative integers, as it is working in hexadecimal and it has range between 0-255
> -1 votes

---
Tags: arduino-uno, arduino-mega, xbee
---


# Question
Title: How does coordinator XBee receive data from router?
I have two XBees S2, one is configured as an API coordinator connected to Arduino and the other as an AT router.

The coordinator sends a frame to the router to switch on a LED. I want to switch off that LED with a button and the router send a message to the coordinator to tell him that it switch off the LED.

How can I do this?

I have one Arduino with the coordinator. I'm asking what I have to put in the script to make the coordinator receive the data.

Here is my code, how the coordinator sends the data to the router:

```
String inputString;
int led = 13;
void setup() {
pinMode(led, OUTPUT);
Seria.begin(9600);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}
if (inputString.length() >0) {
Serial.println(inputString);
if (inputString == "on"){
digitalWrite(led,HIGH);
setRemoteState(5);

}
inputString="";
}
}

void setRemoteState(char value){
Serial.write(0x7E); // start byte
Serial.write((byte)0x0);
Serial.write(0x10);
Serial.write(0x17);
Serial.write((byte)0x0);
// id of recipient or use 0xFFFF for broadcast
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write(0xFF);
Serial.write(0xFF);
// 16 bit of reciepent
Serial.write(0xFF);
Serial.write(0xFE);

Serial.write(0x02);

  Serial.write('D');
  Serial.write('2');

 Serial.write(value);

long sum = 0x17 + 0xFF + 0xFF + 0xFF + 0xFE + 0x02 + 'D' + '2' + value;
Serial.write(0xFF - ( sum & 0xFF) );
Serial.print(sum,HEX);
}

```

# Answer
When you have one working as AT mode, it puts out whatever comes in, it is also called transparent mode.

You should first define which mode you want to use them and start coding.

If you choose AT, load the firmware for both and use Arduino to check the commands and execute tasks (supposing it is connected to the router).

If the task was done correctly, you send an okay message, otherwise, send error. This is a simple task in AT mode, just use Serial:

```
if (led == 1)
   Serial.println("ok");
else
   Serial.println("error");

```

If you choose API mode, it is a little bit different, where you have to mount the packet for sending data and put a message inside it. There are some libs out there you can achieve this.

On the other side, the coordinator will receive the message and interpret it.

If it is in AT mode, just read the serial. In API, you have to decode the packet and check the payload field where the data is located.
> 1 votes

# Answer
To change the state of digital pin 2,D2 set the "value" to 0x05 to switch it HIGH and set the "value" to 0x04 to switch the pin LOW
> 0 votes

---
Tags: arduino-uno, xbee
---


title: LCD Shield and Arduino

text:
# Question
Title: LCD Shield and Arduino
I am trying to use a load cell (https://www.sparkfun.com/products/13331?\_ga=1.55586472.2060096590.1479826091) and an HX711 chip with an arduino and LCD shield to display weight values on the LCD shield when weight is added to the load cell. Does anyone know how I can connect all of these together?

Mainly, how do I connect the HX711 to the arduino while the LCD shield is already on the arduino?

Any help is welcomed , thanks.

Here is the LCD shield I am using I am using:

LCD Shield- https://www.dfrobot.com/index.php?route=product/product&product\_id=51

Arduino- not sure which type of arduino to use.

# Answer
Note: While looking at specifications can infer compatibility, there is no substitute for prototyping. It is always better to try something then ask for suggestions if it does not work as expected.

That said, I would suggest to look at the LCD you specified. The LCD's physical shape appears to lock you into a legacy Arduino Uno layout.

On the LCD's web page is a list of pins used.

On the HX711 sparkfun.com web page is a diagram of pins used when using their HX711 software.

Check if there are any conflicts. Even if there are none, it does not mean there will be no conflicts within the software you will need to run the LCD and the HX711. You will have to either find someone who has successfully done exactly what you want to do or examine all the software involved your self. Of course you could simply prototype the project to see if it works.
> 1 votes

# Answer
It is fairly straight forward.

1. Read the data sheet to find out how you can communicate to hx711. There are tons of example code out there. I have a set of them for my own use as well. The device is quite simple to program too.
2. Find a few pins on the Arduino and configure your code, or others code, to use those pins.
3. I corporate that into your existing code.

That's like how you would approach 99.99 percent of the embedded project - read the data sheet and Code to the data sheet.

If you do run into specific issues, ask them here.
> 0 votes

---
Tags: lcd
---


title: Aurduino Smart Wifi Wall Socket

text:
# Question
Title: 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.

# Answer
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.
> 1 votes

# Answer
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.
> 0 votes

---
Tags: programming, sensors, esp8266
---


# Question
Title: 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: Most compact method of powering Arduino from wall socket

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

Full article from the source, here. 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.

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.

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).
> 6 votes

# Answer
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.
> 2 votes

# Answer
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.
> 0 votes

---
Tags: power, arduino-pro-mini, voltage-level, arduino-mini, electricity
---


# Question
Title: 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

```

# Answer
> 1 votes
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

---
Tags: arduino-mega
---


# Question
Title: 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);
}

```

# Answer
> 1 votes
I'm imagining `SIM900` is a serial stream that supports input methods `available()` and `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()` 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
}

```

---
Tags: programming
---


title: Read value from a file inside SD card

text:
# Question
Title: 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

# Answer
> 1 votes
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
}

```

# Answer
> 0 votes
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.

---
Tags: sd-card, makefile
---


# Question
Title: 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
}

```

# Answer
> 0 votes
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. Also it's not to hard to make this your self for integers and it's a good exercise.

---
Tags: sd-card, makefile
---


# Question
Title: 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.

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;

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

```

# Answer
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 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.
> 2 votes

# Answer
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
> 0 votes

---
Tags: c++, library, build, eclipse
---


title: Where is PORTB defined?

text:
# Question
Title: 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/

```

# Answer
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.
> 4 votes

# Answer
> . Where are those variables defined?

In the device header file. Like other device specific macros.
> -1 votes

---
Tags: pins, port-mapping
---


# Question
Title: 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

# Answer
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.
> 3 votes

# Answer
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.
> 1 votes

---
Tags: arduino-uno
---


title: Problem using IRremote library

text:
# Question
Title: Problem using IRremote library
I am using arduino pro micro 5v 16Mhz. I have built a simple IR transmitter circuit as shown.

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.

# Answer
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.
> 0 votes

---
Tags: ir, wireless, arduino-pro-micro
---


title: Send commands to ESP8266 over WiFi

text:
# Question
Title: 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?

# Answer
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.
> 3 votes

---
Tags: esp8266, wifi, communication
---


# Question
Title: 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?

# Answer
> 0 votes
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"
    }

}

```

---
Tags: arduino-uno
---


title: Arduino Robot won't move

text:
# Question
Title: Arduino Robot won't move
I am building a robot for a school project. I use an Arduino Uno, 2 dc motor's and an Ultra Sonic range measurement module. I want the robot to be autonomous, he has to be able to move around on his own using the Ultra Sonic sensor. Important to mention is that I don't use a MotorShield to control my dc motors. This is my latest version of coding:

---

```
#include <Servo.h> //include Servo library
#include <AFMotor.h> //include DC motor Library
#define trigPin 12// define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);

void setup() {
  Serial.begin(9600); // begin serial communitication
  Serial.println("Motor test!");
   pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
  pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
  motor1.setSpeed(105); //set the speed of the motors, between 0-255
    motor2.setSpeed (105);
}

void loop() {

   long duration, distance; // start the scan
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); // delays are required for a succesful sensor operation.
  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10); //this delay is required as well!
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;// convert the distance to centimeters.
  if (distance < 25)/*if there's an obstacle 25 centimers, ahead, do the following: */ {
   Serial.println ("Close Obstacle detected!" );
Serial.println ("Obstacle Details:");
Serial.print ("Distance From Robot is " );
Serial.print ( distance);
Serial.print ( " CM!");// print out the distance in centimeters.

Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
    motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
      motor2.run (BACKWARD);

}
  else {
   Serial.println ("No obstacle detected. going forward");
   delay (15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
    motor2.run(FORWARD);
  }

}

```

Now I added an ARDUINO MOTOR SHIELD REV3 to control my dc motors. Now the wheels are actually spinning, but after a few turns they stop. I think it is software related, but I am not 100% sure. Also I think I am connecting my motors correct to my motorshield, but don't adress them properly in my code. And I don't have any clue how to solve this problem. Can anybody help me with this?

# Answer
I think your problem is that you connected the positive wire to the 5v pin when it said 5v and not 9v. Also, I am assuming the 6 double AA is in series creating 9v. The thing is, double AA has a lot of amps. I tested it with my multimeter and it has 7 Amps, way to much. What I would do it connect a 9v battery to the voltage in pin-Vin. That pin can take a 9v but not 7 Amps produced by your 6 AA in series. You have 2 dc motors you said.Each is running I am assuming for each of them I notice draw about 1 Amp. 9v will supply enough and be safe. Try connecting a 9v to the Vin pin. I don't think your issue is software related.
> -1 votes

---
Tags: arduino-uno, arduino-motor-shield, software
---


# Question
Title: Automatic subtle colour changing on ws2812b with arduino
I'm creating a wordclock and I'd like to change the ws2812b led strip color slowly, so that it fades from one colour to another. However, I'm new to arduino and I can't get it done and I also could not find anything on this anywhere (probably because of using the wrong keywords)

Currently I have a colour hardcoded like this:

```
void SwitchLED(int MyArray[], int n) {
     for (i = MyArray[0]; i < MyArray[0]+n; i++) {
          leds[i].setRGB((161,57,0);
     }
}

```

(The array in this code are the LEDs that will light up depending on the time I get from a ds3231).

So I would like a (random) starting colour to slowly change to another colour and so on. This in such a way that you will notice it only after a couple of minutes, so very slow and subtle.

I'm using the FastLED libary. I bit of help on this would be appreciated very much.

# Answer
> 0 votes
For the color, you can use the time (`millis()`) as a hue parameter.

```
void SwitchLED(int MyArray[], int n) {
    CRGB color = CHSV(millis()/1024, 255, 255);
    for (i = MyArray[0]; i < MyArray[0]+n; i++) {
        leds[i] = color;
    }
}

```

I used 1024 here to scale the time, so it takes 4 min 22 sec, to go through the hue cycle. And a power of two, should solve a visual glitch on `millis()` overflow.

---
Tags: arduino-nano, rgb-led
---


# Question
Title: A coding problem or improper interrupt usage?
As I should expect(?), the PIR on pin#2 should trigger the trigsensor state at any time the board is running. However, I may get one trigger then nothing else. I have a GSM shield on top of a UNO. I know that I still have some tweaking to do, but I'm trying to solve one issue at a time. Thanks for any insight. The other functions seem to perform correctly. When I enter an incorrect code, the alarms operates properly. When the interrupt is triggered, the alarm response should be the same.

```
///////////////////////// initialize & includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;

boolean started = true;
int PIR_SensorPin = 2;
int Alarm_OutPin = 11; //green
int Light_OutPin = 12; //red
int alarm_count;
boolean volatile trigsensor = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Light_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Light_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("GSM Shield testing."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = READY");
    digitalWrite (Alarm_OutPin, HIGH);
    // PIR as interrupt
    attachInterrupt (digitalPinToInterrupt (2), trigger, RISING);
    //attachInterrupt ((0), trigger, RISING);
  }
  //  started = false; //////////////////////////////////////////////////////////////
  Serial.println ("System Ready, at the keypad loop!");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop() {
  readKeypad();
}

////////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  trigsensor = true;
  started = true;
}

//////////////////////////////// void alarm ///////////////////////////////////
void alarm() {
  Serial.println (started); Serial.println (trigsensor);
  //  digitalWrite (trigsensor, LOW);
  Serial.println("at Alarm");
  // while ((timedelay - time) > 0); Serial.println (time);  time++;
  if ((started == true) && (trigsensor == true)) {
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
    for (alarm_count = 0; alarm_count < 5; alarm_count++) { // Cycle outputs if triggered
      digitalWrite (Alarm_OutPin, HIGH); delay (2000); // On/Off/On/Off/Off
      digitalWrite (Alarm_OutPin, LOW);
      digitalWrite (Light_OutPin, HIGH); delay (2000);
      digitalWrite (Light_OutPin, LOW); // End by turning off light
    }
    digitalWrite (Alarm_OutPin, HIGH);
  }
  else { }
  readKeypad();
}

//////////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    Serial.print("Key_input["); Serial.print(z); Serial.print("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          Serial.print(key_input[i]);
        }
        Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

//////////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();
  }
  else {
    incorrectPIN();
  }
}

//////////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  started = false;
  digitalWrite (Alarm_OutPin, HIGH);
  readKeypad();
}

///////////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
  Serial.println ("@ incorrect PIN ");
  started = true;
  // add time delay before alarm, via keypad??
  alarm();
}

```

# Answer
> 2 votes
None of the code you posted ever sets trigsensor to false, besides the initial value.

---
Tags: interrupt
---


# Question
Title: 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?

# Answer
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.
> 0 votes

# Answer
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.
> 0 votes

---
Tags: esp8266
---


title: Controlling 4 LED strips

text:
# Question
Title: Controlling 4 LED strips
I have 4 single color LED strips which I would like to control individually with one remote controller - turn them on/off an dim them. So far I only have my LED strips (They are about 3.5 meters of length combined), an 80W power supply and an Arduino Uno. I'm new to this kind of stuff. Could you help me with the setup. What parts do I need?

EDIT: So I decided to go with an Arduino Nano. First, I'll try to power up only one strip. My question now is, how to power up the Nano. All the setups I found, have an USB cable connected to the nano to power it up. Can I connect my 12V+ to the VIN?

EDIT2: Take a look at my setup. Is that OK?

Thanks

# Answer
You will need several things.

First I assume that the power supply is a 12V power supply. If it isn't, better to get one (3.5m of leds can be 4.2A, so even a 12V 5A supply is fine). Note: you didn't specify the led size, so the current can vary a lot. But a standard one is a 60 leds/m 5050 leds, which means 60mA/5cm, or 4.2A for a 3.5m strip.

Anyway you will need a 12V power supply to power both the strips and the arduino (through the Vin pin).

You will then need a way to control the leds from the arduino. Since the required current is too high for the arduino, you will need to put a transistor. I tend to prefer nMOS over NPN, but just because of the way I learned them. Anyway just get a low-side transistor (either an nMOS or an NPN) capable of handling the required amount of current (at least a couple amperes, better if they are \>5A) and the proper circuit to turn them on. Usually you will just need one or two resistors. You will need to connect the +12V to the plus terminal of the leds, the drain (or collector) of the transistor to the ground pin of the led you want to control, the source (or emitter) of the transistor to ground and the gate (or base) of the transistor to the arduino through the proper circuit.

Then the remote controller. You did not specify what kind of remote controller you want to use, but usually you can cope with a IR receiver (e.g. the TSOP382 or any other) and the proper decoding. A lot of remote controllers are already mapped in the library IRremote; you just have to read the value it provides; inside the arduino you will need to save the codes for the commands (you will have to train it first) and then simply compare.

This is a generic answer, because you did not provide any details. If, implementing this, you encounter any problem open a specific question with what you did up to that point.
> 2 votes

---
Tags: led, remote-control
---