text:
Serial data affected by interrupt
In my recent project, I have done everything means capture serial data and split it out in proper form.
Until now everything is fine. But when I add another portion of code which contains Interrupt. Now, whenever Interrupt come into the picture, my incoming serial data totally destroy. And when I remove that interrupt portion then everything is fine. But this interrupt is also given one my reading(RPM READING).
I tried out detachinterrupt function, it disables my interrupt then I can't get my RPM READING.
I also tried out interrupts() and noInterrupts() function. But I don't get any results. I think I'm not able to utilize my code with this function.
Here, below my whole code which is a little bit lengthy. But, it's necessary.
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";

String data_LOAD_RI_Json = "";
String data_RPM_Json = "";
String data_INJECTION_TIME_Json = "";

String response = "";
bool begin = false;

char in;
int len = 0;

float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

float LOAD_RI_Json;
float RPM_Json;
float INJECTION_TIME_Json;

//----------------------------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[] = {6.20, 6.26};
float injTime_MAX_LOAD[] = {7.80, 8.06};

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,  RPM0 = 0;
int RPM, Final_RPM;

int RPM_MIN = 400;
int RPM_MAX = 6000;

float injTime_MIN_RPM[] = {6.20, 7.80};
float injTime_MAX_RPM[] = {6.26, 8.06};

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 = 8;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);

  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;

  //------------------JSON SERIAL DATA---------------------//

  while(Serial.available() || !begin)
  {
      in = Serial.read();

      if (in == '{')
      {
        begin = true;
      }

      if(begin)
      {
        response += (in);
      }

      if(in == '}')
      {
        break;
      }

      delay(1);
  }

  len = response.length();

  if(len == 39)
  {
    data_TPS_Json = response.substring(8, 12);
    data_MAP_Json = response.substring(21, 25);
    data_LOAD_TM_Json = response.substring(35, 37);

    jsonMapTps();
  }

  if(len == 52)
  {
    data_LOAD_RI_Json = response.substring(9, 13);
    data_RPM_Json = response.substring(22, 26);
    data_INJECTION_TIME_Json = response.substring(46, 50);

    jsonRpmLoad();
  }

  //------------------------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) >= injTime))
  {
    kInjTime = 0;
    digitalWrite(kPinInj, 0);
  }
}

void countRPM()
{
  RPMpulses++;

  digitalWrite(kPinInj, RPMpulses & 1); // Set or clear kPinInj
  if(RPMpulses & 1)
  kInjTime = millis();  // Store alternate times
}

int getRPM()
{
  Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval);
  RPM0 = RPMpulses &= 1;
  RPMpulses - RPM0;
  return Final_RPM;
}

void jsonMapTps()
{
    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    LOAD_TM_Json = data_LOAD_TM_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(TPS_Json);
    lcd.setCursor(8, 0);
    lcd.print(MAP_Json);
    lcd.setCursor(0, 1);
    lcd.print(LOAD_TM_Json);
}

void jsonRpmLoad()
{
    LOAD_RI_Json = data_LOAD_RI_Json.toFloat();
    RPM_Json = data_RPM_Json.toFloat();
    INJECTION_TIME_Json = data_INJECTION_TIME_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(LOAD_RI_Json);
    lcd.setCursor(8, 0);
    lcd.print(RPM_Json);
    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME_Json);
}

Please add memory statistics.

You haven't specified what hardware you are using.  You need to narrow down the fault. "My data gets destroyed" is not very helpful.  What does you program read when you get an interrupt, how does this vary to normal?  With that number of Strings in memory I agree with @MikaelPatel it is probably memory related.

@MikaelPatel means how many bytes consume by code?

@CodeGorilla Hardware means Arduino Uno or Arduino Mega? Then I used here Arduino Mega. OK... So I have to give a full flow of what I want to do and what happens. Am I right?

Your interrupt handler is short and simple. It should definitely not disturb your program. It does, however, increase memory usage (stack space), which could be the cause of your problems. You should definitely follow Jot's advice about making most variables local and getting rid of String objects.

Finally got the solution. My method of capturing Serial string data is a little bit faulty. And also remove maximum strings and try to declare maximum local variables And use ArduinoJson library for parsing the data.
This is my modified code:
#include<LiquidCrystal.h>
#include <ArduinoJson.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false, finished;

//----------------------------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[] = {6.20, 6.26};
float injTime_MAX_LOAD[] = {7.80, 8.06};

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,  RPM0 = 0;
int RPM, Final_RPM;

int RPM_MIN = 400;
int RPM_MAX = 6000;

float injTime_MIN_RPM[] = {6.20, 7.80};
float injTime_MAX_RPM[] = {6.26, 8.06};

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 = 8;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);

  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;

  //------------------JSON SERIAL DATA---------------------//

  StaticJsonBuffer<100> jsonBuffer;

  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        break;
      }
    }
    delay(1);
  }

  JsonObject& root = jsonBuffer.parseObject(response);

  const char* ActionOne = root["ActionOne"];
  const char* ActionTwo = root["ActionTwo"];

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

  if(root.containsKey("ActionOne"))
  {
    float TPS = root["TPS"];
    float MAP = root["MAP"];
    int LOAD = root["LOAD"];

    lcd.setCursor(0, 0);
    lcd.print(TPS);

    lcd.setCursor(8, 0);
    lcd.print(MAP);

    lcd.setCursor(0, 1);
    lcd.print(LOAD);
  }

 //--------------LOAD/RPM/INJECTION_TIME-------------------//

  if(root.containsKey("ActionTwo"))
  {
    float LOAD = root["LOAD"];
    int RPM = root["RPM"];
    float INJECTION_TIME = root["INJECTION_TIME"];

    lcd.setCursor(0, 0);
    lcd.print(LOAD);

    lcd.setCursor(8, 0);
    lcd.print(RPM);

    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME);
  }

  //------------------------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) >= injTime))
  {
    kInjTime = 0;
    digitalWrite(kPinInj, 0);
  }
}

void countRPM()
{
  RPMpulses++;

  digitalWrite(kPinInj, RPMpulses & 1); // Set or clear kPinInj
  if(RPMpulses & 1)
  kInjTime = millis();  // Store alternate times
}

int getRPM()
{
  Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval);
  RPM0 = RPMpulses &= 1;
  RPMpulses - RPM0;
  return Final_RPM;
}

I'm also trying to capture response as char array but not able to capture it. Please guide me about that otherwise this one string may not cause any heap fragmentation. I am so glad if someone helps me out for this.

You need to clean up the whole sketch. I will try to mention the most important things first.
For an Arduino Uno, this sketch uses 520 bytes RAM and 1528 bytes are free to use for stack and heap. That seems enough but with heap fragmentation it might be a problem, see: Adafruit about an increasing heap
The data_... Strings are only to display something. They can be replaced with normal strings. You could also make a single buffer of a char array for the "response".
The variables that are used in the interrupt routine and also outside the interupt routine should be made volatile.
When the variable begin is false, you still read data with Serial.read(). That can't be right. Could you rewrite that part ?
The variable kInjTime is used to store the millis() time and also to disable it by setting it to zero. That is not good programming since millis() can be zero. It is better to add an extra variable to turn that timing on and off.
The use of digitalPinToInterrupt() is advised when using attachInterrupt(). That makes it easier to see which pins are used.
The function digitalWrite() takes HIGH or LOW, not 0 or 1 and not a bit of a variable, only HIGH or LOW.
Try to use more local variables. You have too many variables as global, which makes it hard to read the sketch.

Oh...Thank you for this points that you mentioned. Let me explain every point.

"data_" strings are displaying the value of data. Suppose serially data {"TPS":"0.40","MAP":"0.95","LOAD":"14"} comes. Then that "data_" strings hold 0.40, 0.95 &  14.

Ok.. Means I have to initialize all that variable made volatile which I used in the Interrupt routine.

Ok, that "Serial.read" portion is capture serial data. Ok, I can try to rewrite that portion.

Ok, means I have to use another variable which holds 0 or 1?

digitalPinToInterrupt ... Ok, that thing I keep in my mind.

But 1 or 0 perform same things as HIGH or LOW do...

Ok, using local variable some time it gives error like variable is not declared in this scope . So, I made all variables global.

LOW and HIGH is 0 and 1, but it is better to make good readable code, than trying to write weird code. Without String objects, the sscanf can be used to split the serial data. The strtok function could be used as well. Or even using array indexes and making the strings zero-terminated is also possible. You could add a boolean variable next to kInjTime. For example: boolean kInjTimeEnable = false; I think the 'a', 'b', 'c', 'd' are local variables, you can declare those inside the for-statement: for ( int a = 0; a < 2..... and there are more variables that are only used locally.


text:
Digispark Serial Port Communication
I am using Digispark ATTiny85 and i need to send and receive data through the serial port of my computer.
Does anyone have an idea as to how do i proceed with sending STRINGS and NUMBERS through the serial port ??
I have read that the ATTINY 85 does not have a serial port.
If that is the case is there any alternative ??

use digikeyboard and your notepad will act as a serial monitor
just burn the program using digikeyboard in digispark examples and connect the attiny to pc and open notepad and it will start acting as a serial monitor.
link to tutorial
https://www.youtube.com/watch?v=Wj7i1fQDeTk

You may use DigiCDC to virtually create a serial device. It's slow but does the job.
A serial-echo program would look something like this:
#include <DigiCDC.h>

void setup() {
  SerialUSB.begin();
}

// the loop routine runs over and over again forever:
void loop() {

  if (SerialUSB.available()) {
    SerialUSB.write(SerialUSB.read());
  }

   //SerialUSB.delay(10);
   /*
   if you don't call a SerialUSB function (write, print, read, available, etc)
   every 10ms or less then you must throw in some SerialUSB.refresh();
   for the USB to keep alive - also replace your delays - ie. delay(100);
   with SerialUSB.delays ie. SerialUSB.delay(100);
   */
}

have read that the ATTINY 85 does not have a serial port.

It depends on your definition of serial port.
From a hardware perspective it has a usi. That can be configured as a uart. Whether it fits your need or not is up to your application. Read the datasheet to be sure.

The ATTiny85 does not have a hardware serial port, but you can use the Arduino SoftSerial library to implement a serial port in software. Have a look at SoftSerial. Or for better performance, including full duplex operation (transmit and receive at the same time) this may be better.

could you help me even further as to how to implement the software serial on the DIGISPARK ATTINY 85 module and use a serial port.

You have a number of options.

Go the DigiCDC/SerialUSB path. Or whatever replaces it.
(harder), use an I2C to serial bridge, SC16IS750. This has a 64 byte buffer limit so input should be short, typically [Esc] or "U" (for firmware update), but basic menu control is possible.
Use SendOnlySoftwareSerial, on a free pin as Tx and hook up an FTDI cable or a serial to USB adapter. This is good for PuTTy, Screen, MiniCom etc.

NB. I have no issues with blowing away the bootloader and just using the usb for power to get option 3 to work.

Its quite simple, you need a program on your PC that will send data (that you type) to the serial port.
If you are on Windows then you want a 'Terminal Emulator' program, I don't know what its called on Linux but it will be along the same lines.
If you are using the Arduino IDE then there is already something built in, the Serial Monitor will do the job.  You don't even need to be using the IDE for programming you should be able to use the monitor anyway.
Also you can write your own application to do it, but don't do that unless you really have to.

the serial monitor is not accessible when using the digispark attiny85 and it gives the error that "COM port is not available" even when the module is connected to the pc

OK, I can see the problem with that plan then. :)

source: Stack Exchange

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

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

sort: votes


text:
Is there a way to define an alias for a hardware Serial
I'm porting some code from Arduino Uno over to a Mega and I want to replace a SoftwareSerial defined in the previous code with one of the built-in UARTs.
Rather than go through and replace all references to the serial port, I'd prefer to create an alias for Serial1. The alias can be a constant.
In my old code, I setup the Software Serial as follows:
//SoftwareSerial HMI(HMIRX, HMITX); // Define software serial for the HMI adapter (RX, TX)

I"m not even sure where to start.

it is simple
#define HMI Serial1

Alternatively: HardwareSerial &HMI = Serial1;

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


text:
Override #define statements in libraries
I'm using a library that, by default, wants to use Serial2 as the interface to a display, however, I'm working with an UNO which only has one serial interface, so the compile fails. I'm trying to use a SoftwareSerial instead, but I can't figure out how to override the #define statement in the library without editing the library.
I'm guessing since the software serial port isn't generated at compile time, I can't.
#include <SoftwareSerial.h>
#define nexSerial HMI
#include <Nextion.h>

SoftwareSerial HMI(8,9);

void setup() {
  // put your setup code here, to run once:

}

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

}

I haven't started writing code yet, can't get past the attempt to redirect the serial interface to a software serial.

You're allowed to modify the header file.  The version I looked at says
#define USE_SOFTWARE_SERIAL //Comment this line for use  HardwareSerial

...but I think he meant "comment this line out to use HardwareSerial".  Or conversely, "uncomment this line to use SoftwareSerial."
Then you just pass your SoftwareSerial instance into the Nextion constructor:
SoftwareSerial HMI( 8,9 );
Nextion nextion( HMI );

void setup()
{
   HMI.begin( 9600 ); // or whatever speed...

However, because you are using pins 8 & 9, I would strongly recommend using AltSoftSerial instead.  It is much more reliable and efficient.  MUCH.
You would have to modify the Nextion files to either (1) search and replace all occurrences of SoftwareSerial with AltSoftSerial, or (2) add a third choice to the author's #ifdef/#endif sections.  For example:
#define USE_SOFTWARE_SERIAL // uncomment this line to use SoftwareSerial
#define USE_ALTSOFT_SERIAL  // uncomment this line to use AltSoftSerial
                            // comment both above  to use HardwareSerial

#if defined(USE_SOFTWARE_SERIAL)
#include <SoftwareSerial.h>
#elsif definied(USE_ALT_SOFTSERIAL)
#include <AltSoftSerial.h>
#endif

class Nextion{
 private:
  void flushSerial();
#if defined(USE_SOFTWARE_SERIAL)
  SoftwareSerial *nextion;
#elsif defined(USE_ALTSOFT_SERIAL)
  AltSoftSerial *nextion;
#else
  HardwareSerial *nextion;
#endif

Do either one of those things in all files that refer to the Nextion serial member; Nextion.CPP certainly needs it.

Thank you. I'll have to go get the newest version of the library, as the one I have doesn't show a software serial option. I'll also look into AltSoftSerial, as I'm having trouble with baud rates above 19200.

You can't.
All you are doing in your code is providing a #define to the instance of the header file that is included in your sketch file. You have no way of modifying the instance that is included in the library's source files.

I was afraid of that. Fortunately, it looks like a new version of the library will work with software serial.


text:
lcd doesn't show any characters , is the problem in the lcd itself?
That's my wiring besides another part of a project ( ultrasonic sensor) which works correctly on the same breadboard, Rs 12 , En 11 , d4 8 , d5 9 , d6 10 , d7 13 I tried to change power of arduino from 5 to 3.3 volt & I tried to use a power adapter
the lcd sometimes show me dark boxes for seconds when I use the potentiometer often in the first row of the display
i used the simulation of tinker cad & it's working but doesn't work on my project & i used the default arduino code with changing the pins number

code :
#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 8, d5 = 9, d6 = 10, d7 = 13;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // Turn off the display:
  lcd.noDisplay();
  delay(50000);
  // Turn on the display:
  lcd.display();
  delay(50000);
}

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

Your code will print on the LCD and immediately turn it off, then wait for 50 seconds and turn it on again. Have you waited the 50s to check if something is shown?

yes I waited for it I doesn't show me any character

In addition to the 6 signals you described, I see 6 more. Allowing that the LCD needs power & ground, and one is the potentiometer, what are the other 3? Do you have a part number for the display, or can you show a definition of its inputs? What is the 10K pullup resistor for?

Vss gnd , VDD 5v , V0 to the middle terminal of potentiometer used for adjusting contrast , RW gnd  , 10 k resistor connected to anode I used it beacuse of the schematic in this link  https://www.hackster.io/MylesBartlett/ultrasonic-security-system-with-object-distance-display-0d7140?f=1#    I tried to remove it but It made the lcd stop working or having power

If you are using 4-bit structure you must use LSB not the MSB. Try your code by connecting your wires to d0,d1,d2,d3 of LCD.

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


text:
Arduino code of making a LED digit display not functioning properly
I want to make an LED one digit display using 14 leds used in pairs so I have 7 pairs which show number. (Similar to the display in calculators). Now the problem is that my code won't function properly. The problem that is arising is that the leds won't go off, all of them would work at the same time, here's the code
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;

void setup()
{
   for(int i = 2; i++ ; i<9)
   {
      pinMode (i, OUTPUT);
   }
}
void _1()
{
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _2()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _3()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _4()
{
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( b, HIGH);
   delay(1000);
}
void _5()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _6()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   digitalWrite ( d, HIGH);
   delay(1000);
}
void _7()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _8()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _9()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _0()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void wait()
{
   digitalWrite ( a, LOW);
   digitalWrite ( b, LOW);
   digitalWrite ( c, LOW);
   digitalWrite ( d, LOW);
   digitalWrite ( e, LOW);
   digitalWrite ( f, LOW);
   digitalWrite ( g, LOW);
   delay(100);
}
void loop()
{
   _0();
   wait();
   _1();
   wait();
   _2();
   wait();
   _3();
   wait();
   _4();
   wait();
   _5();
   wait();
   _6();
   wait();
   _7();
   wait();
   _8();
   wait();
   _9();
   wait();
}

The problem is that it stays at _0 and then never changes. Any suggestions?

Ohk the mistake was found and rectified. Thanks

The for loop in your setup() function isn't quite right. The condition (i<9) and the iterator (i++) need to be the other way round, like this:
for (int i = 2; i<9; i++)
{
  pinMode (i, OUTPUT);
}


text:
Same Arduino Sketch when uploaded from a Linux machine does not work
I am trying out some code using the Arduino IDE. The code basically tries to connect to a server and push some data to it.
When I upload the sketch to the Arduino from Mac (Apple PC running on Mac OS) the code works as expected without an error.
However, when I upload the same code/sketch from a Linux machine on Ubuntu, the arduino does not operate as expected.
I tried taking a diff comparison of the HEX files created in both machines to check whether there are any differences (expecting very few). But found that there a lot of differences.
What am I missing? Why isn't my code working when uploaded via the Linux PC!!!!!

Make sure you're using the correct versions of libraries / IDE you use. Compiler version could be different, but should not matter in most cases. Also you need to give more details, otherwise guesswork is all we can do.

Just got it sorted. Like you said the problem was with the Libraries used. Different version were used in both PCs

'MAC' == Media Access Control, the unique ID given to each Ethernet or WiFi interface. 'Mac' is (sometimes) used as a nickname for Apple, Inc.s desktop and laptop computers. I've edited the question.

I  close this question because it is not reproducible

Got this sorted.
The issue was that different versions of the library was being used in both the PCs. One we made sure that the Linux PC used the same as the MAC one it all worked fine!!!
Thanks Guys


text:
Error when trying to write analog and digital signals from different pins (Arduino UNO)
I'm using the Arduino UNO and started noticing some funny behavior when I was trying a few basic projects. Specifically when trying to write an analog signal through one of the PWM pins, then a digital signal through another.
Using some LED's connected to a few different permutations of pins 8-13, I found that when I have an analog output set for one of the pins (in this case 9, 10, or 11 as they're the only one's of the set capable of PWM) and then try to output a digital signal from a different pin to another LED the digital signal seems much weaker. That is, the LED shines very very dim.
The pins 2-7 work fine.
Does the behavior described above indicate anything wrong with the arduino? are those pins potentially damaged, or is there something I'm not understanding here?
My code:
void setup()
{}

void loop()
{
   analogWrite(9, 255);
   delay(1000);
   analogWrite(9, 0);
   delay(2000);
   digitalWrite(8, HIGH);
   delay(1000);
   digitalWrite(8, LOW);
   delay(2000);
}

It would help to see your actual circuit. Are you using resistors? Are they all the same value? Ditto with the LEDs – all the same, or behave the same if you swap a dim one with a bright one?

Sounds like an electrical problem. Please post your schematic and also your code.

just put the schematic and code up. also I've tried switching out the LED's but I'm still got the same result.

Is the code shown here complete? I don't see any output setups.

I tested your code and it does indeed behave the way you said. But that is because you have not declared any pins as output.
analogWrite does this for you automatically in the library, however digitalWrite does not. This is because sending a digital pin HIGH when it is INPUT turns on the internal pull-up resistors. These are around 50k. Thus you will only see very dim output on the LED. Add this line to setup:
 pinMode (8, OUTPUT);

(And preferably pin 9 as well, just in case you decide to change to digital writes later).

The pin groups your describe are on different ports of the chip which have different current sourcing ratings.
I'm sure you'll find an even brightness using similar LEDs on all pins and using a 1K res in series with each led to limit current.
Also , to ensure the sourcing transistors are ON within the chip, be sure to declare the pins as output when required.


text:
Arduino how to loop a method
Hello I have a method where when you press a button a string is compared with a substring to see if the string contains the substring. The problem is when I load in the string I call the check button press and substring comparing method. Which only ever happens once. I want to know how I can keep calling the method. It sounds simple but it isn't.
void loadPrograme(){
   file = SD.open("/classes/basic.txt", FILE_READ);
   Serial.print("Reading, Checking and Compiling \n\n\n");

   for (int i = 0; i < arraysize; i++) {
      while (file.available()) {
         character23 = file.read();
         if (character23 == '\n') break;
         if (character23 != '^') {
            content += character23;
         }
      }
      content.trim();
      if (content != "") {
         result[i] = content;
         content = "";
         delay(1000);
      }
   }
   for (int i = 0; i <arraysize; i++) {
      if(result[i].substring(0,5) == "print"){
         printlnMethod(result[i]);

      }else
         if(result[i].substring(0,5) == "delay"){
            delayMethod(result[i]);
         }else
            if(result[i].substring(0,11) == "buttonPress"){
               buttonMethod(result[i]);

            }

   }

   file.close();
}

void buttonMethod(String s){
   s = s.substring(s.indexOf('{') + 1);
   s = s.substring(0, s.lastIndexOf('}'));
   String btn =" ";
   String daction = " ";
   String indaction = " ";
   btn= s.substring(s.indexOf('"')+1 );
   btn= btn.substring(0, btn.lastIndexOf('"'));
   daction = s.substring(s.indexOf(',')+1);
   daction = daction.substring(0, daction.lastIndexOf('('));
   indaction = s.substring(s.indexOf('~')+1);
   indaction = indaction.substring(0, indaction.lastIndexOf('~'));
   int buttonpressed;
   if(btn == "BUTTON_PIN_ENTER"){
      buttonpressed = 2;
   }else if(btn == "BUTTON_PIN_LEFT"){
      buttonpressed = 3;
   }else if(btn == "BUTTON_PIN_RIGHT"){
      buttonpressed = 4;
   }else if(btn == "BUTTON_PIN_DOWN"){
      buttonpressed = 5;
   }else if(btn == "BUTTON_PIN_UP"){
      buttonpressed = 6;
   }else if(btn == "BUTTON_PIN_ACTION"){
      buttonpressed = 7;
   }

   int btncheck = digitalRead(buttonpressed);
   if(btncheck == LOW){
      if(daction.substring(0,5) == "print"){
         printlnMethod(indaction);

      }else if(daction.substring(0,5) == "delay"){
         delayMethod(indaction);
      }
   }
}

}

So basically it loads in the txt file into the string array and loops through it and reads each line. each line is executed. for example if it get the substring of buttonpressed it goes to the buttonmethod(). The problem is in the button method. I want to have the button method keep looping until the button is pressed but it only runs through that method once. How can I keep running threw this method until the button is pressed?

Fix code format.

Help us out by telling us about the syntax and semantics for the script language.

what do u mean?

Do you want to keep calling the buttonMethod() or keep calling the digitalRead portion of the buttonMethod()?

the buttonmethod

Please give examples of a script and what it means, what should be executed.

Testing for string equality with '==' is a mistake: https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c  The '==' operator on strings will compare the pointers to the strings rather than their content and likely always fail the if() tests.
To loop and block on the last bit, if that is what you mean, you might try:
   int btncheck;
   ...
   while(btncheck = digitalRead(buttonpressed)){ // wait for button
      if(strcmp(daction.substring(0,5),"delay")){
         delayMethod(indaction);
      }
   }  // blocked until btncheck == LOW
   if(strcmp(daction.substring(0,5), "print")){
         printlnMethod(indaction);
   }

This has the blocking on non-pressed button feature, but also has the same logic as the original.  If the string equality tests do not match, it appears you want to do nothing and quickly pass on.
To loop buttonMethod(), put it in a loop:
while(1)buttonMethod(string);

If you want to condition on getting the button press that corresponds with the string, I'd make buttonMethod return a value and loop conditionally on that:
int buttonMethod(...
    int retVal = 0;
    ...

  if(btncheck == LOW){
     retVal = 1;
     ...
  }
  return(retVal);
}

...
while(!buttonMethod(result[i]));  // wait for the button

Might need to debounce the button.


text:
Arduino Blink two LEDs without Delay(amount of repetitions)
Arduino community.  I have had experience with Arduino for 3 years now and have finally come to the conclusion to get rid of the delay function entirely.
Below is the code to blink two LEDs a complete 10 times.  The problem is that the setup() doesn't repeat like a loop(), which means it doesn't last a long enough to find a time difference between PreviousMillis and CurrentMillis because it runs once; thus, defeating the idea of blinking a LED in the setup().  But, I have researched ways to imitate the loop() with while loops; I have used Adafruit's method to spice things up(Constructors and classes!),
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview.
But I need a little help because it doesn't work, instead, it blinks forever(Mission half-complete =)).
Notice how I have used while loops in the Update(), which is located within the Flasher Class, to mimic a loop() until the condition becomes true.
The problem is, I don't know why this code doesn't work and what to do from here.
The ultimate goal is to blink the LEDs at pin 12 and pin 13 a total of 10 Times, instead of repeatedly blinking for an eternity.  I am using an Arduino Uno R3 and a Serial baud rate of 115200.
Ignore what I did in the loop().  It's the same function as the setup() code, instead, the led blinks an eternity (unfortunately), when a value of "1" is typed.
    class Flasher{
    // Class Member Variables
    // These are initialized at startup
    int ledPin;      // the number of the LED pin
    long OnTime;     // milliseconds of on-time
    long OffTime;    // milliseconds of off-time

    // These maintain the current state
    int ledState;                 // ledState used to set the LED
    unsigned long previousMillis;   // will store last time LED was updated
    unsigned long currentMillis = 0;

  public: Flasher (int pin, long on, long off)
{            // Constructor - creates a Flasher
    // and initializes the member variables and state

      ledPin = pin;
      pinMode(ledPin, OUTPUT);

      OnTime = on;
      OffTime = off;

      ledState = LOW;
      previousMillis = 0;
    }

    void Update(int a){
      // check to see if it's time to change the state of the LED
      for (int i = 0; i < a; i++) {
        while ((currentMillis - previousMillis <= OnTime) || ((currentMillis - previousMillis <= OffTime))) {
          currentMillis = millis();

          if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
          {
            ledState = LOW;  // Turn it off
            previousMillis = currentMillis;  // Remember the time
            digitalWrite(ledPin, ledState);  // Update the actual LED
          }
          else if ((ledState == LOW) && (currentMillis - previousMillis >=OffTime))
          {
            ledState = HIGH;  // turn it on
            previousMillis = currentMillis;   // Remember the time
            digitalWrite(ledPin, ledState);   // Update the actual LED
          }
        }
      }
    }
};

Flasher led1(12, 100, 400);
Flasher led2(13, 350, 350);

void setup(){

  Serial.begin(115200);
  led1.Update(10);

}

void loop(){

   /* if (Serial.available()) {
      String str = Serial.readString();

      if (str.substring(0, 1).equals("1")) {
        led1.Update(10);

      }
  }*/
}

SimpleTimer and similar millis()-based timer libraries are made for just this kind of job. SimpleTimer even allows you to specify a number of repetitions as well. The gist of it is you set a timer to an interval and perhaps a number of repetitions, and a callback function to be called at the end of each interval. Your main code just calls the timer's update function, "run()" in this case, very frequently. Your callback function will be called at the appropriate times. This is one of the easiest ways to implement this kind of job, mimicking foreground/background but without the complexity of interrupts and interrupt service routines.

I've modified your sketch so that when you instantiate a LED Flasher object with a 4th argument, it flashes forever. If you instantiate a Flasher object with 3 arguments, use the Start() function to start the LED flashing the number of times you specify. Just call it once, not repeatedly in the loop() function (e.g. when a button is pressed). You can call the Start() function again and specify a different number of flashes. You can have multiple LED flasher objects. Each object can have different on/off times. Some LEDs can flash forever, and some the number of times specified.
EDIT
I've added a few functions in the class to make it more versatile: Stop(), SetPinHighTime(), SetPinLowTime() and SetFlashForever().
class Flasher{

  // Class Member Variables. These are initialized at startup.
  byte ledPin;
  byte ledState;
  byte flashForever;
  unsigned int flashCounter;
  unsigned long highTime;
  unsigned long lowTime;
  unsigned long previousMillis;

  // Constructor. Create a LED Flasher object.
  // Initialize the member variables and LED state.
  public:

  Flasher(byte pin, unsigned long on, unsigned long off, byte continueFlashing = 0){
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    highTime = on;
    lowTime = off;
    ledState = LOW;
    flashForever = continueFlashing;
    previousMillis = 0;
  }

  void Update(){

    // Check to see if it's time to change the state of the LED.
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= highTime) && ((flashCounter > 0) || (flashForever == 1))){
      ledState = LOW;
      previousMillis = currentMillis;        // Remember the time.
      digitalWrite(ledPin, ledState);        // Update the actual LED.
      if(flashCounter > 0){flashCounter--;}  // Update the flash counter.
    }
    else if((ledState == LOW) && (currentMillis - previousMillis >= lowTime) && ((flashCounter > 0) || (flashForever == 1))){
      ledState = HIGH;
      previousMillis = currentMillis;        // Remember the time.
      digitalWrite(ledPin, ledState);        // Update the actual LED.
      if(flashCounter > 0){flashCounter--;}  // Update the flash counter.
    }
  }

  void Start(unsigned int flashNumberOfTimes){
    flashCounter = flashNumberOfTimes * 2;
    flashForever = 0;
    ledState = LOW;
    digitalWrite(ledPin, ledState);
  }

  void Stop(){
    Start(0);
  }

  void SetPinHighTime(unsigned long pinHighTime){
    highTime = pinHighTime;
  }

  void SetPinLowTime(unsigned long pinLowTime){
    lowTime = pinLowTime;
  }

  void SetFlashForever(byte oneOrZero){
    flashForever = oneOrZero;
    if(oneOrZero == 0){Start(0);}
  }

  void SetPinToInput(){
    pinMode(ledPin, INPUT);
  }

};

// Used for testing purposes only.
byte doOnce = 0;
const byte led1PinNumber = 2;
const byte led2PinNumber = 3;
const byte led3PinNumber = 4;

// Instantiate LED Flasher Object(s).
// e.g. Flasher object_name(Pin Number, ON Time, OFF Time, OPTIONAL Flash Forever);

// Three argument constructor.
// The number of times to flash the LED is specified
// when you call the Start() function. The LED will NOT
// start flashing until you call Start().
Flasher led1(led1PinNumber, 10, 990);
Flasher led2(led2PinNumber, 100, 400);

// Four argument constructor.
// Flash an LED forever. This will start the LED flashing immediately.
Flasher led3(led3PinNumber, 1000, 1000, 1);

void setup(){}

void loop(){

  // Call the Update function as fast as possible.
  led1.Update();
  led2.Update();
  led3.Update();

  // Test output. Flash 3 LEDs with different on/off times.
  // Use the Start() function to flash 2 of the LEDs X number
  // of times, then restart each LED flasher object with
  // a different number of flashes. Set 1 LED to flash forever,
  // then stop it and start a different LED flashing forever,
  // altering the flash rates of one LED before restarting it.
  // Finally, set the 3 LED pins to INPUT.

  // Start the led1 object 4 seconds after Arduino startup.
  if(millis() > 4000 && millis() < 5000 && doOnce == 0){
    led1.Start(3);  // Flash the LED 3 times.
    doOnce = 1;
  }

  // Start the led2 object 5 seconds after Arduino startup.
  if(millis() > 5000 && millis() < 6000 && doOnce == 1){
    led2.Start(5);  // Flash the LED 5 times.
    doOnce = 0;
  }

  // Restart the led1 object 10 seconds after Arduino startup.
  if(millis() > 10000 && millis() < 11000 && doOnce == 0){
    led1.Start(7);  // Flash the LED 7 times.
    doOnce = 1;
  }

  // Restart the led2 object 15 seconds after Arduino startup.
  if(millis() > 15000 && millis() < 16000 && doOnce == 1){
    led2.Start(9);  // Flash the LED 9 times.
    doOnce = 0;
  }

  // Stop flashing the led3 object.
  // Start flashing the led1 object forever.
  if(millis() > 30000 && millis() < 31000 && doOnce == 0){
    led3.SetFlashForever(0);
    led1.SetFlashForever(1);
    doOnce = 1;
  }

  // Stop flashing the led1 object.
  // Start flashing the led3 object forever and change
  // it's flash rate.
  if(millis() > 50000 && millis() < 51000 && doOnce == 1){
    led3.SetPinHighTime(250);
    led3.SetPinLowTime(500);
    led3.SetFlashForever(1);
    led1.SetFlashForever(0);
    doOnce = 0;
  }

  // Stop flashing the led3 object. No LEDs should be flashing.
  if(millis() > 60000 && millis() < 61000 && doOnce == 0){
    led3.Stop();
    doOnce = 1;

    // My test shield has one High and one Low LED per pin.
    // Set the pins to input to turn off the Low LEDs.
    led1.SetPinToInput();
    led2.SetPinToInput();
    led3.SetPinToInput();
  }

}

From pure C++ point of view, this implementation might be correct, however, 1) for Arduino, setup() get call in Arduino main() after some initialisation of hardware, it is why Arduino advocate to have initialise hardware with a begin() method than using the construct (it happened before the initialisation of the hardware).

For C++, if your implementation of class methods within the Class, by default, all the methods would be considered as inline methods. what this means is that for example the update() will be inserted as inline at where it get called. It is therefore necessary to separate the Class prototype from implementation.

@hcheung - The constructor takes care of initializing the required variables when the object(s) are instantiated. If you could answer the OP's question with the code required to implement the begin() function, I would up-vote such an answer.

@hcheung - 2) "It is therefore necessary to separate the Class prototype from implementation. - Says who? I can write "Arduino code" any way I like, so long as it compiles, is the smallest compile size, and works perfectly. I think the compiler is smarter than me, and can take code written by millions of different users world wide, and make it work just fine :) Feel free to answer the question with a better answer.

Well, I didn't say it doesn't work, and for Arduino, people may not care about the size of the code much either, in fact, most of Arduino users think of learning C++ is optional. It is not part of compiler optimisation, it is how C++ is defined. "A class's member functions can be declared inline, either by using the inline keyword or by placing the function definition within the class definition". You can check any book about C++ from Bjarne Stroustrup.

@hcheung - I don't care what the books say. I'm retired, so I write code the way I like. If you have a "proper" answer, which agrees with your book(s), do tell...

Let us continue this discussion in chat.

For such a simple task, the code is very complex.
First, write a piece of code that blinks the LEDs if sufficient passage of time has been met.
You can implement a blink counter, either in the main loop or the blink routine mentioned earlier.
Should be fairly simple.
edit: here is how I would have implemented it.
//blink the led for a given number of times
//cnt: number of times of the blinks needed
uint8_t led_blinky(uint8_t cnt) {
    static uint8_t led_cnt=0;       //blinky count
    static uint32_t millis_prev=0;  //previous millies

    if (led_cnt>=cnt) return led_cnt;   //return blink count
    if (millis() > millis_prev + LED_ms) {    //enough time has passed
        millis_prev += LED_ms;                      //update the time
        digitalWrite(LED, (digitalRead(LED)==HIGH)?LOW:HIGH);       //flip led
        led_cnt+=1;                 //increment the led count
    }
    return led_cnt;                 //return blinky count
}

the code itself is fairly self-explanatory -> the only (marginally) tricky part is how it maintains timing accuracy over a long period of time. in this particular implementation, the test is done inside the led_blinky() routine so it is self-contained -> it does return the number of blinks that have been executed.
Here is the execution of performing 100ms blinks 4 times:

I'd like to proposes a couple of changes to @VE7JRO's implementation.
For C++, it is perfectly normal to initialise an Class instance via its construct, however, for Arduino, the setup() get call in Arduino main() after some initialisation of the hardware, including pin definition, etc., it is why Arduino advocates in Arduino Style Guide for Writing Libraries to use a begin() to initialize a library instance (it is perfectly okay to use the construct to setup some variables but not for something like pinMode() in the construct). Because very often the creating of a Class instance happened before the setup() get called.
With this in mind, the propose changes:
class Flasher{

  // Class Member Variables. These are initialized at begin().
  byte ledPin;
  byte ledState;
  byte flashForever;
  unsigned int flashCounter;
  unsigned long highTime;
  unsigned long lowTime;
  unsigned long previousMillis;

  public:

  Flasher() {}

  begin(byte pin, unsigned long on, unsigned long off, byte continueFlashing = 0){
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    highTime = on;
    lowTime = off;
    ledState = LOW;
    flashForever = continueFlashing;
    previousMillis = 0;
  }
  ....
};

To use the Class:
Flasher led1;
Flasher led2;
Flasher led3;

setup() {
  led1.begin(led1PinNumber, 10, 990);
  led2.begin(led2PinNumber, 100, 400);
  led3.begin(led3PinNumber, 1000, 1000, 1);
}

Another change has to do how C++ defined inline function or method. "A class's member functions can be declared inline, either by using the inline keyword or by placing the function definition within the class definition". What this means is that all the functions defined in the Flasher class in this case are implied as inline methods. so when led.update() get call, it is placed as inline code by the compiler at where it get call (and multiple times). There are certain methods that are perfectly okay and in fact should be inline, for example, SetPinHighTime(), and SetPinToInput() would actually benefit from being inline, but you will probable don't want the update() method to be inline. In order to do that, create a Class prototype and have the methods that you'd want to be inlined implemented within the Class definition, but separate the implementation of update() method.
#ifndef FLASHER_
#define FLASHER_
#include "Arduino.h"

class Flasher{

  // Class Member Variables. These are initialized at startup.
  byte ledPin;
  byte ledState;
  byte flashForever;
  unsigned int flashCounter;
  unsigned long highTime;
  unsigned long lowTime;
  unsigned long previousMillis;

  public:

  // All methods are inline, except update()

  Flasher() {}
  void begin(byte pin, unsigned long on, unsigned long off, byte continueFlashing = 0){
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    highTime = on;
    lowTime = off;
    ledState = LOW;
    flashForever = continueFlashing;
    previousMillis = 0;
  }

  void Update();

  void Start(unsigned int flashNumberOfTimes){
    flashCounter = flashNumberOfTimes * 2;
    flashForever = 0;
    ledState = LOW;
    digitalWrite(ledPin, ledState);
  }

  void Stop(){ Start(0); }

  void SetPinHighTime(unsigned long pinHighTime){
    highTime = pinHighTime;
  }

  void SetPinLowTime(unsigned long pinLowTime){
    lowTime = pinLowTime;
  }

  void SetFlashForever(byte oneOrZero){
    flashForever = oneOrZero;
    if(oneOrZero == 0){Start(0);}
  }

  void SetPinToInput(){ pinMode(ledPin, INPUT); }

};
#endif

Define update() method separately in implementation Flasher.cpp:
#include "Flasher.h"

Flasher::update() {

    // Check to see if it's time to change the state of the LED.
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= highTime) && ((flashCounter > 0) || (flashForever == 1))){
      ledState = LOW;
      previousMillis = currentMillis;        // Remember the time.
      digitalWrite(ledPin, ledState);        // Update the actual LED.
      if(flashCounter > 0){flashCounter--;}  // Update the flash counter.
    }
    else if((ledState == LOW) && (currentMillis - previousMillis >= lowTime) && ((flashCounter > 0) || (flashForever == 1))){
      ledState = HIGH;
      previousMillis = currentMillis;        // Remember the time.
      digitalWrite(ledPin, ledState);        // Update the actual LED.
      if(flashCounter > 0){flashCounter--;}  // Update the flash counter.
}

I hope this will help to make the class better and better understanding on C++ and Arduino, and next time when you read the source of an Arduino library, you had better understanding on why the library implement its class and methods the way it does.

So, you took my 3 lines of code used to instantiate the 3 objects (via the constructor), added 3 more lines to it, which accomplishes the same thing as the original 3 lines did. Did you compare the compile size / memory usage for your method VS my method? -1 for taking simple code and making it more complex.


text:
Can I control analog IO pins using Yun Linux
2 days back I bought Arduino Yun. I'm able to flash Led on 13 pin. And I'm able to flash Led on Bread board connected to A0. I'm able to run linux commands.
Now I want control A0 pin using Linux/Python program. Is this possible? I read many documents. But I didn't find thing related to this.
How I  can flash the LED using Linux programs?

Do you mean using the Linux side of the Yun or using a Linux computer?

@bersch - please undo your edit which changed the subject of the question.

There are several libraries which will do this for you. Basically, you should upload a special sketch onto the Arduino, which listens to the serial port, and performs the I/O that the Linux chip requests. Libraries which can do this are

Firmata
Autobahn
LininoIO

I am looking for the same thing. The only thing I have come up with is that you can use the Bridge Library and use curl on the Linux side to read or write the pins

Could you develop your answer further, e.g. with sample code that shows at least where to start?

Bridge makes sense, but how would curl command help?

I haven't used a Yun before, but here is my understanding.
The Yun is really 2 separate computers with a bidirectional serial port between them.
The output pins are on the Arduino side. If you want to control Arduino pins from the LINUX side, you need to come up with a simple command syntax for communicating between the 2 computers and write code on both sides that supports that command syntax.
Say the command is:
digitalPinx=n;

Where x is the pin number, and n is a value, 0 or 1. (for digital pins). For a PWM output pin you could use a command analogPin and values of n from 0 to 255:
analogPinx=n;

On the LINUX side you'd just send that command through the serial port to the Arduino.
On the Arduino side, you'd write a loop that would wait for data to come into the serial port from the LINUX chip. If it gets data, it would read it into a buffer until it saw a semicolon.
Then it would break the data into separate lines using the semicolon as a delimiter, search for "digitalPin" or "analogPin", parse the data between the command and the semicolon for the values, and issue the digitalWrite or analogWrite command using those values.

how to send a command to from linux to arduino?

I don't know the specifics. I bet there are example sketches on the Arduino site that show you how to send data between the two processors though. You would need to write code for both sides that defines a command syntax. The Yun's LINUX processor would send a series of bytes to the serial port and that represented a command to the Arduino processor. The Arduino processor would listen on it's serial port, and when it saw the command, it would use it to change the state of pin A0.

Suggest starting with the  the Mailbox examples in the Bridge library. Specifically the example
http://www.arduino.cc/en/Tutorial/MailboxReadMessage
Which shows how to transfer messages to the Arduino processor. It does discuss how to fire the curl process from the command line.

The simpliest thing I've found, is using the command "lininoio start"
then you can use nodejs with https://github.com/ideino/ideino-linino-lib and you no need to worry with the sketch part anymore, just javascript :-)
http://smag0.blogspot.fr/2017/07/smagyun.html


text:
OSX upload error: avrdude: ser_open(): can't open device "/dev/cu.mydev" : Resource Busy
I'm trying to upload the blink script to my unnamed Arduino-like board. However, the USB port appears to be busy.
This is all the output I get:
Archiving built core (caching) in: /var/folders/43/7_h5zwcs1csdr2dc635m1yq40000gp/T/arduino_cache_942504/core/core_arduino_avr_uno_51f02b7210b938436b779d1c032618e1.a
De schets gebruikt 928 bytes (2%)  programma-opslagruimte. Maximum is 32256 bytes.
Globale variabelen gebruiken 9 bytes (0%) van het dynamisch geheugen. Resteren 2039 bytes voor lokale variabelen. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "/dev/cu.mydev": Resource busy

I've tried all solutions I could find on internet, but they haven't solved my issue. The main difference with my error and online solutions/errors is that I only have this error. Other people experienced extra errors which enabled the debugging of the problem.
Can anyone help me please?

Not nearly enough information to answer this question.  Why are you using that particula device, for instance?

I think my available serial ports were insufficient or something. I installed the ch34* driver which allowed an additional device showing up. Here's the download: http://www.wch.cn/download/CH341SER_MAC_ZIP.html
Then I selected this port and I finally could upload.

If this is the answer, you should not have tagged your question "arduino-uno" as that board does not use a CH34x.  The erroneous tag and board description have been removed from your question, so that people with actual Arduino UNO boards do not mistakenly install inappropriate drivers as a result of reading your question/answer.

strangely it did solve my issue

If you have some random clone that uses a ch34x rather than the Arduino Uno you originally claimed, potentially it could.   But if your board has an ATmega8u2/ATmega16u2 on it, then you are mistaken in thinking this had anything to do with it.

I have a genuine Arduino Uno. Perhaps I changed something else in the process, but I can't recall. After installation of this driver, I had access to an additional port which worked.

Then this answer is wrong, misleading, and should be deleted so that it does not cause others to install inappropriate software, especially software that runs with kernel privileges.

I checked the readme file. I got the port by this installer. So this in fact solved my issue. You're right about the Arduino. I checked it on the site of the reseller and they in fact sell clones. So mine is not genuine. Thanks for the help. Would you recommend another solution than installing this ch34 driver, or is this the only way?

The solution might be bad in theory but it's good in practice. Worked for me, with a couple of different genuine boards and random ebay clones. But if you have a better suggestion @ChrisStratton, do please post it for us.

@stib -This answer is WRONG AND MISLEADING.  A CH340 drivers is of ABSOLUTELY NO HELP WITH GENUINUE BOARDS.  It can only help with cheap boards that use a CH340/CH341 chip.


text:
Arduino zero Error: unable to find CMSIS-DAP device
I am uploading a test sketch(Blink) to my new Zero(with Wifi101 shield) and when I press Upload in the IDE, the Console says the following:
Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Zero (Programming Port)"
Open On-Chip Debugger 0.9.0-gd4b7679 (2014-10-03-00:26)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
adapter speed: 500 kHz
adapter_nsrst_delay: 100
cortex_m reset_config sysresetreq
Error: unable to find CMSIS-DAP device
Error: No Valid JTAG Interface Configured.
Error: No Valid JTAG Interface Configured.

I am using the Zero programming port.

Unless you mean that this works normally and only breaks when the shield is present, remove the shield for the moment and take it out of your title.  Then edit the the output of lsusb into your question.  Also look for messages in dmesg after re-plugging the board, and consider trying another cable.  There could also be permission issues, but I'd expect a different error message then.

I just tried it without the wifi101 shield, and I got the same error.

And lsusb shows what???  And dmesg ???

Experiments with a different CMSIS-DAP show that this is probably a permission issue - openocd does not distinguish between the absence of a CMISIS-DAP programmer vs. lack of permission to access one which is present.  The usual solution is to create or install an appropriate udev rule and then restart udev or the system and replug the device.  This does not seem to be well documented, so one might say the board is not a well  supported product at present.

I had exactly the same error with the same board. Running the IDE as root solved the problem. So, Chris was right pointing out a permission issue.
I found more information here : http://bitofahack.com/post/1437909576
Then I added the file /etc/udev/rules.d/98-openocd.rules :
ACTION!="add|change", GOTO="openocd_rules_end"
SUBSYSTEM!="usb|tty|hidraw", GOTO="openocd_rules_end"
ATTRS{product}=="*CMSIS-DAP*", MODE="664", GROUP="plugdev"
LABEL="openocd_rules_end"

I then ensured that I was member of group plugdev.
udev looks for changes in his rules directory so you don't have
to restart it.
I plugged the board again and it worked.
Note that you can force udev to read the rule files again by entering :
sudo udevadm control --reload

I had to do this because I first made a mistake in the rule file.
Hope this helps.

98-opencd.rules >>> 98-openocd.rules

missing closing double quote ? LABEL="openocd_rules_end >>> LABEL="openocd_rules_end"

Yes. Fixed. Very old message...


text:
Elegoo "Uno R3" not being recognized in any computer anymore
I used to be able to use my Elegoo Uno R3, just fine. It worked with my computer no problem. Except I used the USB cable on a power bank and now the Uno isn't being recognized on any computer. I tried uninstalling and re-installing the IDE and drivers. But nothing works. I don't even get the serial 2.0 USB in the device manager. the Uno itself works. The orange and green lights stay on continuously when plugged in and It's still outputting the code I put in it before it stopped connecting to my computer. Any help to be able to fix my Uno. The button on the UNO doesn't seem to do anything either.

Worth trying a different cable, but likely you've damaged it.  That power bank should be considered suspect, and probably not used again with anything you value.

I did try a different cable but no luck


text:
I fried the AMS1117 voltage regulator on my Arduino Clone, is this the cause?
I had the 12V DC power jack plugged-in all the time, and "to make things more exciting" I also plugged-in the "data" USB whenever I had a new sketch to upload. Is this combination a big no-no, or is my step-up converter to blame?
I am completely new to this stuff but now when thinking of it those 12V from the power jack + 5V from the "data" USB probably violate this clause:
If using more than 12V, the voltage regulator may overheat and damage the board.

Original Arduino boards work fine with both USB and the barrel jack plugged in. However, I think you are having a clone, as the original doesn't use the AMS1117. Depending on what you have connected, the voltage regulator can get quite hot.

@Gerben indeed it is a clone... and given I have ordered an original since this sounds like a promising news to me, thank you very much sir :)

Did you have anything else connected to the 12V DC supply at the same time?

@EnricBlanco nothing else

The "problem" with the AMS1117 voltage regulator is the amount of current they can safely provide drops as the input voltage rises. I'm a Arduino noob, so I looked at the data sheet for the AMS1117 series of voltage regulators. There is a formula: PD=(VIN-VOUT)(IOUT) and Note 2: which says the maximum power dissipation for the SOT-223 package is 1.2 W.
The best case scenario is to use an input voltage of 6.5 volts. (6.5-5)(0.8)=1.2W. This gives you 0.8 amps maximum output. If you use a 12 volt power supply: (12-5)(0.1714)=1.2W. This only gives you 0.1714 amps maximum output.
I'm not sure what kind of power jack you are using, so I'll give you an example of one that I used in a project. It says input 120VAC, output 12VDC, 200ma. The problem is, it actually puts out 20VDC open circuit with no load.
The data sheet gives a maximum input voltage of 15 volts but that would only provide a maximum of 120 mA output.

What if I have a 3.7V battery to supply power for a 3.3V ESP8266 (WiFi module)? Would a AMS1117 between the battery and the module be good at making sure the voltage is at ~3.3V?

The datasheet for the 3.3V AMS1117 gives a maximum dropout voltage of 1.3V, so 4.6V would be the lowest voltage you should apply to it. Another option is to use the battery with a Buck-Boost DC DC 0.9-6V to 3.3V Step-UP Step-Down Converter Board such as this one: www.aliexpress.com/item/Auto-Buck-Boost-DC-DC-0-9-6V-to-3-3V-Step-UP-Step-Down-Converter/32756017955.html.

Probably not. There is nothing fundamentally wrong with what you're doing - it's within the design parameters. In particular:

12V is within the 7-12V recommended range specified for that input. Yes, it means the regulator will get hotter, but the AMS1117 is supposed to be current limited and thermally limited so should just start shutting down if it supplies too much current or gets too hot. As this answer suggests, it would be wise to limit it to 1.2W, which is 171mA. That's plenty for the Arduino itself, so you'd only be running into trouble if you have other peripherals to power.
The Arduino Uno has circuitry specifically designed to disconnect the USB's 5V rail if the external power supply is present. This is really only to protect the USB supply from being damaged by the external power supply - the Arduino doesn't care as long as it is getting 5V from somewhere. The USB data function is independent of whether the 5V comes from the USB's 5V rail or the 5V generated from the external supply you provide. The AMS1117 itself, according to its (various) datasheet, has no design susceptibility to an alternate 5V supply being on the output.

Finally, there's an alternate reason for the failure. We've also been using an Arduino Uno clone with the AMS1117, and have also been supplying 5V external (directly to the 5V rail in our case) as well as connecting to USB for programming. We've also had an AMS1117 fail, despite operating everything within normal limits. Our symptoms are that the OUT pin is shorted to the GND pin. Removing the regulator restores full functionality.
Based on various reports around the Internet of suspect behaviour and doubtful provenance of these chips on the clone boards, I would suggest that a faulty IC might be the root cause.

authors: Никита Макаров


text:
Interfacing Hex keypad with arduino
I was trying to interface my hex keypad with Arduino. I declared rows as input and columns as output. When I initialize three of the four columns as HIGH and one as LOW, and detect the button pressed as LOW in the corresponding row, it works fine. That is, it detects the button when its corresponding row and column is LOW. But, when I reverse the condition, i.e. when I try to detect the button pressed when its corresponding row and column is high while others are low, it does not work as expected.
I really want to know why is this happening?
The code that works:-
int row[]={6,7,8,9};
int col[]={10,11,12,13};
int i,j;
int col_scan;
void setup()
{
   Serial.begin(9600);
   for(i=0;i<=3;i++)
   {
      pinMode(row[i],OUTPUT);
      pinMode(col[i],INPUT);
      digitalWrite(col[i],HIGH);
   } }
void loop()
{
   for(i=0; i<=3; i++)
   {
      digitalWrite(row[0],HIGH);
      digitalWrite(row[1],HIGH);
      digitalWrite(row[2],HIGH);
      digitalWrite(row[3],HIGH);
      digitalWrite(row[i],LOW);
      for(j=0; j<=3; j++)
      {
     col_scan=digitalRead(col[j]);
     if(col_scan==LOW)
     {
        keypress(i,j);
        delay(300);
     }}
   }}
void keypress(int i, int j)
{
   if(i==0&&j==0)
      Serial.println("1");
   if(i==0&&j==1)
      Serial.println("2");
   if(i==0&&j==2)
      Serial.println("3");
   if(i==0&&j==3)
      Serial.println("A");
   if(i==1&&j==0)
      Serial.println("4");
   if(i==1&&j==1)
      Serial.println("5");
   if(i==1&&j==2)
      Serial.println("6");
   if(i==1&&j==3)
      Serial.println("B");
   if(i==2&&j==0)
      Serial.println("7");
   if(i==2&&j==1)
      Serial.println("8");
   if(i==2&&j==2)
      Serial.println("9");
   if(i==2&&j==3)
      Serial.println("C");
   if(i==3&&j==0)
      Serial.println("*");
   if(i==3&&j==1)
      Serial.println("0");
   if(i==3&&j==2)
      Serial.println("#");
   if(i==3&&j==3)
      Serial.println("D");
}

the code that doesn't work:-
int row[]={6,7,8,9};
int col[]={10,11,12,13};
int i,j;
int col_scan;
void setup()
{
   Serial.begin(9600);
   for(i=0;i<=3;i++)
   {
      pinMode(row[i],OUTPUT);
      pinMode(col[i],INPUT);
      digitalWrite(col[i],LOW);
   } }
void loop()
{
   for(i=0; i<=3; i++)
   {
      digitalWrite(row[0],LOW);
      digitalWrite(row[1],LOW);
      digitalWrite(row[2],LOW);
      digitalWrite(row[3],LOW);
      digitalWrite(row[i],HIGH);
      for(j=0; j<=3; j++)
      {
     col_scan=digitalRead(col[j]);
     if(col_scan==HIGH)
     {
        keypress(i,j);
        delay(300);
     }}
   }}
void keypress(int i, int j)
{
   if(i==0&&j==0)
      Serial.println("1");
   if(i==0&&j==1)
      Serial.println("2");
   if(i==0&&j==2)
      Serial.println("3");
   if(i==0&&j==3)
      Serial.println("A");
   if(i==1&&j==0)
      Serial.println("4");
   if(i==1&&j==1)
      Serial.println("5");
   if(i==1&&j==2)
      Serial.println("6");
   if(i==1&&j==3)
      Serial.println("B");
   if(i==2&&j==0)
      Serial.println("7");
   if(i==2&&j==1)
      Serial.println("8");
   if(i==2&&j==2)
      Serial.println("9");
   if(i==2&&j==3)
      Serial.println("C");
   if(i==3&&j==0)
      Serial.println("*");
   if(i==3&&j==1)
      Serial.println("0");
   if(i==3&&j==2)
      Serial.println("#");
   if(i==3&&j==3)
      Serial.println("D");
}

There could be any number of reasons, but we'd need to see a schematic and some code, or at least the representative parts of each. There's not enough information here to be able to tell.

To use unipolar switches as inputs, you need pulling resistors to give the input pin a defined value when the switch is open.
The ATmega has software configurable internal pullups.  Even if these are not configured, implementation detail may (or may not) yield a very weak unreliable pullup effect.
There is no configurable pulldown on the ATmega.  To operate in that direction (with a switch to high) you would need external pulldown resistors.
A few matrix keyboards include diodes, to combat some of the confusion which results when multiple keys are pressed in a simple matrix.
Also, you should add a tiny delay between driving and reading, in order to allow for capacitive delay.


text:
Swapping 5V and GND for a 2 wire motor
I have a 2-wire brushed DC motor in a servo housing which either pushes left or right (and "center" when unplugged).
To push to one side I connect a wire to 5V and the other to GND, to push to the other side I just need to swap the wires.
How can I achieve this with the arduino without any physical rewiring?

I think you need arduino motor shield.

Click Here
Just click on above link, you find a good tutorial about arduino motor shield. I hope it might be helpful.

The pictured L293-based shield is obsolete by at least a decade, look for something with a more modern solution like a TB6612FNG to get decent performance, especially if using batteries.

Thanks! I was able to try the Arduino Motor Shield R3 and it works as intended.

What you want is called a H-bridge, and it is what a standard Arduino motor shield does.


text:
error while loading libtinfo.so.5 - SOLVED
I just installed the 1.6.7 version and want to upload it a sketch to Arduino UNO hardware. I get error message:

/home/pali/Irataim/TarBalls/Arduino/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory

I'm on Gentoo linux operating system.
How can I solve this problem?
By following this link:
https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6
I just add tinfo USE flag to ncurses package, re-emerged it and can run Arduino IDE that I emerged from Gentoo repository.

(Install dependencies with emerge -avq sun-jre-bin crossdev) Run equery belongs libtinfo.so , if the library exists then try symlinking the libraries: ln -s /lib64/libncurses.so.5 /usr/lib/libtinfo.so.5 and
ln -s /usr/lib/libtinfo.so.5 /usr/lib/libtinfo.so.

I did so, but there is no libtinfo.so library.

equery belongs libtinfo.so there is none?

Exactly! There is none libtinfo.so out there.

@PalCsanyi in the stack exchange system, questions are marked resolved not by editing the title, but by accepting an answer.  If none of the provided answers matches your solution, provide your own and accept that, however it does look like at least one of them matches what you said you did.

@sa_leinad please do not edit questions in a way that pushes the most important part of the error message off the screen.  Adding a requirement to manipulate a scroll bar to view the actual issue is the opposite of making a question clear.

@ChrisStratton thanks. good point. I'll know that for next time!

Install libtinfo5, the terminfo library.
If that doesn't help, you can try to debug the problem yourself. First,
check which libtinfo avrdude is looking for:
ldd arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude_bin | grep libtinfo

On my Ubuntu, I get this:
libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fa74a888000)

Next, see where your libtinfo is installed:
find /lib /usr/lib -name 'libtinfo*'

On my system I get:
/lib/x86_64-linux-gnu/libtinfo.so.5
/lib/x86_64-linux-gnu/libtinfo.so.5.9

Do you have any discrepancy between the two?

I just installed terminfo package, the Haskell bindings to the terminfo library and try to upload again a sketch. I get the same error message:  arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory. However, I'm using now the just downloaded arduino-1.7.8-linux64 package.

@PalCsanyi: Then I do not have the solution, but I added some hints to help you debug the problem.

I tried followings on my Gentoo linux:
ldd arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude
not a dynamic executable
find /lib /usr/lib -name 'libtinfo*'
There is no output.

@PalCsanyi this topic refers to  have similar problem and got it solved using a symbolic link to libncurses. Take look: https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6

@PalCsanyi: OK, I downloaded arduino.org's tarball (I was testing with Ubuntu's arduino package). Their avrdude is a shell script: the real avrdude is avrdude_bin. I updated the answer with the output I get from their avrdude_bin on a 64-bit system. You said you installed the terminfo package, did you install version 5? What files does it provide that have the ".so" extension? No libtinfo.so.5 in sight?

My installed terminfo package name is:
dev-haskell/terminfo and the installed version is:  0.4.0.0(19.15.39 2016-03-02).
Description of this package is: Haskell bindings to the terminfo library.
When I run
ldd Irataim/TarBalls/Arduino/arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude_bin | grep libtinfo
I get:
libtinfo.so.5 => not found

No grep libtinfo:
linux-vdso.so.1 (0x00007ffee67f4000)
libusb-1.0.so.0 => /lib64/libusb-1.0.so.0 (0x00007f6fe415e000)
libusb-0.1.so.4 => not found
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f6fe3f42000)
libm.so.6 => /lib64/libm.so.6 (0x00007f6fe3c46000)
libreadline.so.6 => /lib64/libreadline.so.6 (0x00007f6fe39fb000)
libncurses.so.5 => /lib64/libncurses.so.5 (0x00007f6fe37a4000)
libtinfo.so.5 => not found
libc.so.6 => /lib64/libc.so.6 (0x00007f6fe3409000)
libudev.so.1 => /lib64/libudev.so.1 (0x00007f6fe31e3000)
/lib64/ld-linux-x86-64.so.2 (0x00007f6fe4376000)

@Personagem
Indeed, there is a solution for me. Thanks!!
https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6

Thanks, sudo apt install libtinfo5 worked for me.

You have to rebuild sys-libs/ncurses with tinfo USE flag turned on. (You can also make a symlink: libtinfo.so -> libncurses.so, but it's not elegant solution).
Firstly, check if you have a record for ncurses in any file in /etc/portage/package.use. If not, create a file /etc/portage/package.use/ncurses with such content:
sys-libs/ncurses tinfo

then, rebuild ncurses:
emerge -av sys-libs/ncurses


text:
Send newline through serial monitor
I know I can send a newline using the option in the bottom right:

But why doesnt it work to use the option 'No line ending', and send a '\n' or '\r\n' after the text using the arduino serial monitor?

The backslash escape encoding for special characters is a feature of double quotes in some programming languages, shells, and other parsers.  It is not normally a feature of live text input - an "end user" human typing a backslash is assumed to mean it literally.
"Live" input of a carriage return or newline is more traditionally done with the return/enter key, or with the corresponding control codes - CTRL-J for newline and/or CTRL-M for return.  I don't know that the Arduino IDE's Serial Monitor supports either of these, at least once you select "no line ending"


text:
HM-10 discovery issue
i am not able to detect any android device on my bluetooth HM-10 module which is connected to arduino. i am able to see my bluetooth module on my android phone. but i want to see android phones on arduino serial monitor for that i used AT+DISC? command. it shows AT+DISCS and than AT+DISCE with a 2 second interval. help me to solve the issue
thanks in advance

The HM-10 is a BLE-only device.
Android phones do not normally transmit BLE advertisements, so there is normally nothing about an Android phone for it to discover.
The exception would be if you have software on a late Android version with the capability, which you have set up to intentionally transmit BLE advertisements, or else if software you put on your Android phone is actively responding to advertisements you had the HM-10 transmit.
Essentially, you are expecting something that his not normal behavior, but will only be achieved by adding your software on both devices.

Good answer, it's like my laptop seeing all wifi connections. But my accesspoint not seeing all (unconnected) devices. It depends on which device is the "searcher" and which is "advertising itself". In practice, most devices don't do both.

Detecting the physical Bluetooth layer is likely different from detecting the underlying protocol.  So it might be that the Arduino code is waiting until it sees a specific Bluetooth protocol.  I am guessing that it wants to use a serial Bluetooth protocol (as oppose to music or some other protocol).  You have not given enough details to determine if this is the problem.  However, I would next test your devices / hardware by loading up what is assumed to be working code on both your Android and your Arduino to test the connection.  The code in this project looks promising:

is there any way such that i can make the protocol compatible since my hm-10 is getting detected on various mobile devices. my project requirement is such that i have to detect the mac id of other phones near the range of hm-10.

MAC is a feature of the phone's WIFI. I wouldn't expect the MAC information to be available on the Bluetooth port without an application on each phone specifically written to do tHis.

@st2000 MAC addresses are not confined to wifi, Bluetooth has its own as well.


text:
The Right Com Port (COM 7) is NOT Showing
I just finished a camp for the arduino and the arduino uno that they gave us is not working with my computer even though everything was working on their computers. I am trying to upload with the same schematic, same Arduino, and the same code. It is not wanting to upload even after changing in the preferences to the same com Port. I have tried updating the drivers, but Windows 7 64 bit s saying this error message : This device cannot start. (Code 10) .  Also, there is an exclamation mark in the device manager but how hard I try, it doesn't go away.

-1 for improperly tagging this "arduino-uno" when what you actually have is a different design with a different USB serial solution.  You should accept your own answer for the ch340 based board you apparently have.

I found out that I could not use the arduino drivers because I am using a DCcduino uno that has a separate driver.

The DCcduino Uno clone uses a CH340 USB-serial chip. The Arduino IDE doesn't include the driver for that chip because none of the official Arduino boards use it. You need to download and install the driver from http://www.wch.cn/download/CH341SER_EXE.html

The Right Com Port (COM 7) is NOT Showing

It would appear that Microsoft Windows does not necessarily assign the same COM port for a given device from machine to machine.  It is usually up to the user to map which COM port is being used for which device.  Some applications which work with specific devices have been known to "search" for that specific device and automatically connect to the correct COM port.

...saying this error message : This device cannot start...

There is this Microsoft Web Page here about this error.
More specific help may be found here.  In particular, this passage looks promising:

On Windows 7 (particularly the 64-bit version), you might need to go
  into the Device Manager and update the drivers for the Uno or Mega
  2560. Just right click on the device (the board should be connected to your computer), and point Windows at the appropriate .inf file again.
  The .inf is in the drivers/ directory of the Arduino software (not in
  the FTDI USB Drivers sub-directory of it).


text:
Avrdude Verification Error while flashing Arduino Mega code
I'm working with an Arduino Mega 2560 and am getting the following error at compile time:

avrdude: verification error, first mismatch in byte 0x0000 0x14! =
  0x25 avrdude: verification error; content mismatch

I've already changed the COM port and also restarted an IDE.

This is not a compilation error but an error when verifying the programmed memory.

Do you have the Board set correctly? Tools->Board.

Do you have an old Mega2560 and have !!! somewhere in your code?

First mismatch in byte 0x0000. Is that the first byte that goes wrong ? That means that not even a single byte passes the verification ? Perhaps the cause is one of these: 1) A cheap clone with a bad bootloader. 2) An old bootloader. 3) A bug, perhaps a bug with the size of the code or ram, for example the code at the border of 32k or 64k. 4) Maybe the voltage of the Arduino board is too low. Measure it. It must be above 4.5V. 5) Maybe a bad usb cable. 6) Wrong usb driver. 7) Board is too cheap and is missing decoupling capacitors.

I have seen this myself. It turned out that coms were a little distorted. If you have access to one, use an oscilloscope to view the waveforms of the 4 ISP pins.

Similar to: https://arduino.stackexchange.com/q/52798/19409 https://arduino.stackexchange.com/q/30946/19409 https://arduino.stackexchange.com/q/59837/19409

I have made Jot's comment into an answer in the hope that it helps someone.

First mismatch in byte 0x0000. [This is] the first byte that goes wrong. That means that not even a single byte passes the verification.
Perhaps the cause is one of these:

A cheap clone with a bad bootloader.
An old bootloader.
A bug, perhaps a bug with the size of the code or ram, for example the code at the border of 32k or 64k.
Maybe the voltage of the Arduino board is too low. Measure it. It must be above 4.5V.
Maybe a bad USB cable.
Wrong USB driver.
Board is too cheap and is missing decoupling capacitors.


text:
ESP8266 proper power circuit for avoid reset issue
I am using an ESP8266 in a project which will be on for at least 18 hours a day. I'm using an Arduino 3.3V power supply to feed the ESP8266.
The issue I'm facing is a reset issue. It sometimes disconnects from the hotspot automatically.  I have heard this could be because the ESP8266 draws more power than the Arduino's regulator is able to supply.
I want to know what will be the proper circuit to power the ESP8266.
I know I have to use an AMS1117 regulator, but I also know I have to use capacitors too. How would I configure the AMS1117 with capacitors to properly power an ESP8266?

A simpler solution for those who don't want to deal with wiring up a regulator is to get the "nodemcu" style of ESP8266 module having its own regulator.  These typically also have a USB serial interface, though determine which chip is used and its driver situation on your computer's operating system before purchasing one.

The ESP8266 power problem keeps coming up, so we need a canonical question to close the re-asks as duplicates against.  I think post-edits this could be a candidate, but perhaps there are other choices.

You don't "need" an AMS1117 regulator. You need a power source that can supply enough current.  One example is an AMS1117-33, although it's not a great one as far as efficiency goes (though it is simple).
The basic circuit is to have a 10µF capacitor on both the input and output of the regulator - that should be enough for most uses.

simulate this circuit – Schematic created using CircuitLab
Powered from more than around 5V the AMS1117-33 would need some heatsinking.  You can also add some smaller (100nF) capacitors in parallel with the 10µF ones if you want to improve high frequency response.
You can pick modules up with this circuit on from eBay for a dollar.
A better power source would be a "buck" switching regulator. These are far more efficient and generate much less heat.  It's harder to search for these on eBay since all the AMS1117-33 modules seem to be labelled erroneously as "buck" regulators (which they so are not!), so be careful when looking around. A true "buck" regulator will have an inductor on it. Here's one example.

Add " -ams1117" to your search query in eBay, to remove listings that has AMS1117 in the title.

@Gerben I did - that's how I got the example one I listed. Still not foolproof though.

The spec says that an AMS1117-3.3 can deliver 1A, but realistically that only works if you run it off 5V. The ESP draws ~400mA when it is transmitting, and at 12V the AMS is dissipating 8.7V x 0.4A =  3.48W. That makes it kinda hot, and it tends to cut out.  A buck regulator, even a tiny one using MP2307, is a much better bet. set the voltage first before connecting to the ESP!

ESP8266 draws ~170mA when transmitting


text:
Feedback Request: HID USB to Bluetooth Relay
Bluetooth Relay Project:

Develop a USB to bluetooth adapter for my mechanical keyboard. Using a USB host shield, have an Arduino Pro Mini read keyboard usb commands and repeat them over bluetooth.

I have minimal experience with Arduino and circuitry, from my perspective this project seems pretty straight forward plug and play of the hardware components.
I plan to use the following hardware:
Hardware:

Arduino

Arduino Pro Mini 328 - 3.3V/8MHz
Sparkfun Products: 11114

Bluetooth HID module

BlueSMiRF HID
Sparkfun Product: 10938 ($25)

USB Host Shield

USB Host Shield for Arduino Pro Mini
circuitsathome ($20)

Power Source

USB Phone power block
Output: 5v 1000mA

Total Cost: $55
I will be connecting the USB module by following the write up here and will be connecting the USBHost shield by following this guide and this guide
Does anyone have any comments/suggestions/concerns/words of wisdom before I start to order stuff?


text:
Connecting an Arduino to a telephone line?
I would like to connect my Arduino Uno to a telephone line in order to answer a call, record a sequence of DTMF tones, generate a DTMF tone in response, and hang up.
The telephone line uses a standard RJ11 connector. When a touch-tone phone is connected to the line, it receives one of two rings:

a standard ring, which signals an incoming call
a shorter "two-ring" sequence which signals a call from a local intercom

I would like my Arduino to listen for the "two-ring" sequence and only answer those calls.
How would I go about connecting my Arduino to the telephone line? Is there a shield designed for this purpose? I know I can use the tone() function to generate the DTMF tones, but I'm assuming I would need to perform some form of Discrete Fourier transformation in order to "read" the DMTF tones from the other end of the line.
Any suggestions would be appreciated.

Be careful when connecting directly to the phone line. There can be huge spike on the line (e.g. lightning strikes). If you've ever opened e.g. an ADSL modem, you'll see there are quite a few protection components on it (sparkgaps, movs, magnetics).

In the UK it is illegal to connect anything to the phone line that hasn't been certified. You might want to check your local regulations too.

You can interface arduino to telephone line using MT8870D chip. This IC can decode DTMF tones. Below is a reference schematic from the datasheet.

Another popular design floating on the internet is below:

There are pre-build modules available from futurelec :

You can use Holtek HT9200 IC to encode DTMF that can be interfaced with Arduino. Below is the reference schematic from its datasheet.

You'll need some hardware assistance for the DTMF detection and generation; I doubt many Arduinos (you didn't say which, but maybe ARM?) have the horsepower to run an FFT (and deliver the results while anyone still cares....)* tone()may not be precise enough in frequency for DTMF detection by the calling device; you'll have to check that out. A quick search finds a number of articles on building or buying tone detectors and generators.
Ringing pattern detection is a little easier but you'll still probably want to sense the ringing and convert it to a level in hardware, rather than tracking the instantaneous line voltage and trying to distinguish in software between noise, ringing, noisy ringing, and various degrees of quiet.
* But maybe this Hackaday project can give you some alternate and computationally feasible ideas.

Hmm... I guess I hadn't given enough thought to the amount of processing required for DFT/FFT. Although (as your link suggests) I'm only sampling for a very small set of frequencies.