text:
Is there any way that the two 'different' programs of arduino can be run one after another keeping each one separate?
I have made a 8*8*8 led cube using arduino. I have found two different codes from different developers having different animations in them. i wanted to combine them and get to run all the animations at once. Both the codes have some similar function names and some are different as well. I wanted to know if i can keep both these separate from each other yet run them one after another. Almost all parameters are different including setup() of both codes. Please help

Define "after". An Arduino program runs constantly until you tell it otherwise (by removing the power, pressing reset, uploading a new program, etc). There is no "after" to an Arduino program.

You can achieve this fairly simply by using namespaces. Inside a namespace, symbols are relative to that space. So you could put all of your first sketch into the namespace sketch1, and all of the second sketch into the namespace sketch2 (assuming it all fits, of course).
Now you can call the first sketch's setup and then loop, by qualifying it with the namespace name as illustrated below.
// FIRST SKETCH

namespace sketch1
{

  // FUNCTION PROTOTYPES

  void func1(int a, int b);
  void func2();

  void setup()
  {
    Serial.begin (115200);
    Serial.println ("Inside sketch1 setup");
    func1 (5, 6);
  }

  void loop()
  {
    Serial.println ("Inside sketch1 loop");
    delay (1000);
    func2 ();
  }

  void func1(int a, int b)
  {
    // some function
  }

  void func2()
  {
    // some other function
  }

} // end of namespace sketch1

// SECOND SKETCH

namespace sketch2
{

  // DECLARE FUNCTIONS BEFORE CALLING THEM

  void func3(int a, int b)
  {
    // some function
  }

  void func4()
  {
    // some other function
  }

  void setup()
  {
    Serial.begin (115200);
    Serial.println ("Inside sketch2 setup");
    func3 (7, 8);
  }

  void loop()
  {
    Serial.println ("Inside sketch2 loop");
    delay (1000);
    func4 ();
  }

} // end of namespace sketch2

// MAIN LOOP AND SETUP

void setup()
{
  pinMode (10, INPUT_PULLUP);
  if (digitalRead (10) == HIGH)
  {
    sketch1::setup ();
    while (true)
      sketch1::loop ();
  }
  else
  {
    sketch2::setup ();
    while (true)
      sketch2::loop ();
  }
}   // end of setup

void loop()
{

} // end of loop

In my example I am testing a pin (10) to see if sketch1 or sketch2 should run.

yet run them one after another

Yes, well sketches normally keep running inside loop forever, so you would need a way of deciding when to exit the sketch and run the other one. My example shows how you can choose between one or the other based on a digital input.

I tried it but it is showing that the functions are not declared in this scope.

Important note re function prototypes
It looks like the IDE's automatic generation of function prototypes doesn't work inside namespaces. Thus you need to do either:

Make your own function prototypes (that is the function declaration without the actual function code) - see sketch 1 above; or
Declare a function before it is used (sketch 2 above)

If this is someone else's code you may find it easier to just add the function prototypes as required. When you get the error message, find the function it is referring to, copy the "declaration" part, eg.
void foo (int a, int b)

Add a semicolon, eg.
void foo (int a, int b);

Then put that before it is called. Make sure it is still inside the namespace.

can I call the setup if first namespace then some func. respective to that namespace then call the setup of second namespace and call func. from that namespace and keep all this in an infinite loop?

Well, you can do that, but you need to realize what each sketch is doing. For example if sketch1 turns some pins to output, but sketch2 assumes they are still inputs, then you need to undo that.

And what is it to wrapup a function and 'how' to do it.

You need to inspect the sketches and see what they have done, so you can "undo" it. For example:
void wrapup ()
  {
  // set all pins to inputs and LOW
  for (int i = 0; i < 20; i++)
    {
    pinMode (i, INPUT);
    digitalWrite (i, LOW);
    }
  // if Serial used
  Serial.flush ();  // flush output
  Seral.end ();    // stop serial hardware

  // and so on

  }   // end of wrapup

I tried it but it is showing that the functions are not declared in this scope. The program didn't compile 2nd Q: And will sketch1::loop (); will run the loop of sketch1 forever?. I want it to run once and next sketch should run. The 2 codes should run one after another indefinitely without any condition. how shall i achieve that?. Or can you please provide me your email so that i can send you the codes and you could combine them if you've got a bit of time. please it would be a great help as i am a newbie and will truly appreciate your work.

Nick's code compiles for me. The problem is with your changes. Try and fix them, and if you can't, create a minimal, complete, verifiable example and post a new question.

Regarding making them one one after the other, I don't think there's a one-size-fits-all answer for that. Really you need to understand what the code is doing, and find a way to adjust it. That's the fun of Arduinos anyway.

As I said in my answer, most Arduino sketches are designed to loop forever. So to make one proceed after the other you have to redesign that paradigm. And no, I'm not giving you my email address.

See amended answer about generating function prototypes.

Thanks. that problem was solved by doing as you said. One problem still persists. one of the two codes that i mentioned also has custom libraries attached to it and has .h, .cpp files too. when compiling there are errors like undefined references. first code does not have any custom libraries.  so i removed the namespace from the second code(having custom libraries) and only called sketch1 in the second code like sketch1::setup ();. But this too gives only one error which is  undefined reference to `sketch1::SPIClass::begin()'

The #include statements need to be at global scope (not in a namespace). After all you need the library anyway and there won't be name clashes with the libraries (or hopefully not anyway). There is no point in hiding that inside a namespace. Also the automatic library detection that the IDE does probably won't work if you have the #include in a namespace.

Thank You @NickGammon The Cube now works fine and the program runs smoothly.

Just one more question i wanted to ask. At the main (final) setup and loop, can the functions which are inside the namespaces be called individually?.My Aim is to run one namespace sketch after another 'unconditionally'(the present condition is dependent upon the pin (switch) to be 1 or 0). i.e in the main loop can i call the setup if first namespace then some func. respective to that namespace then call the setup of second namespace and call func. from that namespace and keep all this in an infinite loop. Or is there any way you know to run these sketches one after another unconditionally.

Namespaces are just ways of organizing function (and variable) names. You can certainly call from one namespace to the other. For example inside namespace sketch2 you could call sketch1::setup ();. Just be careful that any resources used in one sketch are released before you switch to the other one. You might make a function wrapup that releases resources (for example, setting any output pins back to input).

Yes, the same problem is occuring to me.I first call sketch1::setup (); then  call a function from sketch1 like sketch1::func1 ();. then i call setup of sketch 2 and then func if sketch 2 for eg.  sketch2::setup (); then sketch2::func6 ();. here what happens is , func1 runs properly but func6 does not run.And  Suppose i first call setup and  fun6 from sketch1, funcs in sketch2 dont run after them.(i.e the functions called first called sketch work and the functions from next called sketch dont run) .how to solve this problem. And what is it to wrapup a function and 'how' to do it.

See amended answer.

Re. your wrapup(): you don't need to digitalWrite(i, LOW) after pinMode(i, INPUT) (doesn't hurt either...), as pinMode() takes care of both the PORT and DDR registers when setting the pin as either INPUT or INPUT_PULLUP. Only when you set a pin to OUTPUT it leaves the PORT register in whatever state it was before.

@NickGammon In the past I did something similar, but I did it in this way: void (*loop_ptr)(); /* in the setup */ if (..) { setup1(); loop_ptr = loop1; } else { setup2(); loop_ptr = loop2; } /* in the loop */ void loop() { loop_ptr(); }. This is because outside the loop there is some code in the arduino main. Another way would be to set a variable and inside the loop call void loop() { if (use_prg1) loop1(); else loop2(); }. What do you think? PS sorry for double comment, but I mistakenly pressed enter before and now I can't modify the previous one

That's OK if it works, but if you have other functions (say from example code) which happen to have the same name then you get name clashes. The namespace idea isolates each bunch of code into a non-clashing area.

@Nick, your answer is masterful.  As usual.  I always learn something new from your posts and I will keep this in mind.  But I think it might be a bit overwhelming for this user.

@SDsolar Thanks! It may or may not be too complex for some users, but it might give others an idea for how to fairly simply merge two sketches that have the same function or variable names. :)


text:
What are devices in this picture?
I don't know the name of those. Please advise me.
Thanks very much.

Post a link to the video you took the screenshot from.

The things on the right are just terminal blocks.

Wires? Pins? Connectors? What has this to do with Arduinos?

The left item looks like some Arduino clone with custom connectors. The right hand item looks like a scale model of a J Class Freighter.

oh, thanks all.
@Mark Smith: it's terminal blocks :D

Item all the way to the right are these Excellway ET25 2/3/5 Pins Spring Terminal Block Electric Cable Wire Connectors

It's a Seeeduino Lotus (or a clone of it).

source: Stack Exchange

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

sort: votes


text:
Problem with PWM interference
I have a following code
  #include <Servo.h> //library for servo drive
  int MotorAPinA = 9;   //pin number for DC drive
  int MotorAPinB = 10;  //pin number for DC drive
  Servo myservo; //create object myservo, class servo from Servo library

void setup() {
  // put your setup code here, to run once:
  pinMode(MotorAPinA, OUTPUT);
  pinMode(MotorAPinB, OUTPUT);
  //myservo.attach(6); //pin number for servo output
  myservo.write(65);
}

void loop() {
  analogWrite(MotorAPinA, 240);
}

This very code works only partly.
If I comment line
myservo.attach(6)

then I got my DC drive working.
If I uncomment this line, my Servo goings crazy (effect looks like myservo.write(0) constantly), until I comment line
analogWrite(MotorAPinA, 240);

and then I got my servo working properly.
While myservo.attach(6) is uncommented, DC drive doesn't work (with uncommented analogWrite).
So, basically, I can have or PWM or Servo working simultaneously, but not both
Any ideas? Arduino Uno R3, Arduino 1.8.1.

Well, your PWM outputs are both on 16b Timer/Counter 1 and the servo is attached to the 8b Timer/Counter 0. So my guess is that 8bit counter has too low resolution for driving the servo and it uses Timer/Counter 1 in full 16b mode for better precision instead (PWM uses just 8bits from 16). Also Timer/Counter 0 is used for counting millis, so its settings can't be changed anyway.
For the confirmation you can either:

use pins 5 and 6 (TC0) or/and pins 3 and 11 (TC2) and for the servo use pin 9 or 10
You can read the values of TC1 configuration registers and according to the datasheet you can figure out what mode is currently used.

EDIT:
So on the Uno board is used Timer/Counter 1 for timing purposes:
  if(timer == _timer1) {
    TCCR1A = 0;             // normal counting mode
    TCCR1B = _BV(CS11);     // set prescaler of 8
    TCNT1 = 0;              // clear the timer count
    TIFR |= _BV(OCF1A);      // clear any pending interrupts;
    TIMSK |=  _BV(OCIE1A) ;  // enable the output compare interrupt
    timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service);
  }

So no PWM on the OC1A nor OC1B in normal mode and the channel A is taken by Servo.

`
#include <Servo.h> //library for servo drive
int MotorAPinA = 6;   //pin number for DC drive
int MotorAPinB = 5;  //pin number for DC drive
Servo myservo; //create object myservo, class servo from Servo library
void setup() {
// put your setup code here, to run once:
pinMode(MotorAPinA, OUTPUT);
pinMode(MotorAPinB, OUTPUT);
myservo.attach(9); //pin number for servo output
myservo.write(65);
}
void loop() {
analogWrite(MotorAPinA, 240);
//analogWrite(MotorAPinB, 0);
}
`
somehow `` doesn't code code

Now it works. Servo on Timer/Counter1 16 bit (10 and 9 pins), PWMs on Timer/Counter0 0 bit (6 and 5 pins), and there are still free 11 and 3 pins of Timer/Counter2

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


text:
Make something happen on a continous input just once and for a specific amount of time
My project is very complicated, but here is a visual synthesis

The input actually comes from a kinect, that detects a person position through Processing, which I connected via Serial to Arduino.
Whenever my trigger is activated, a character is sent to arduino.
What I need to make everything work properly is, upon the said input, some lines of code have to be executed once and for a specific amount of time. And upon repeated input, these lines must not be executed until the input changes.
A semplified version would be: I press a button, led turns on for one second and then turns off (even if i'm still pressing it). led doesn't turn on again until i stop pressing and press again. Obviously in my project the input is the character received via serial and the output is the motor to turn on for some time, and then turn off.
I wanted to make the serial thing specific because i think it makes the thing a little bit trickier than the led example.

Your button analogy falls apart immediately when you try to convert it to serial. Could you delete it, please, and explain exactly how you want it to behave, considering that characters being received on the serial port are discrete events?

Well, te problem is actually the same provided that you write correctly the first program.
How did you solve the button problem? My suggestion is to use a simple state machine:
const byte ledPin = 13;
const byte buttonPin = 2;

const int onTimeMs = 1000; // The time the led should be on

// In this state the board waits
// for the user input
#define STATE_WAITING 0
// In this state the button was
// pressed (so the led is on)
#define STATE_PRESSED 1
// In this state the board is waiting
// for the button to be released
#define STATE_WAITREL 2

byte currState;
unsigned long pressTime;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  currState = STATE_WAITING;
}

void loop() {
    switch (currState)
    {
    case STATE_WAITING:
        if (digitalRead(buttonPin) == LOW)
        {
            digitalWrite(ledPin, HIGH);
            pressTime = millis();
            currState = STATE_PRESSED;
        }
        break;
    case STATE_PRESSED:
        if ((millis() - pressTime) > onTimeMs)
        {
            digitalWrite(ledPin, LOW);
            currState = STATE_WAITREL;
        }
        break;
    case STATE_WAITREL:
        if (digitalRead(buttonPin) == HIGH)
            currState = STATE_WAITING;
        break;
    }
}

In this case you can be in three states: waiting for the button press, waiting for the led to turn off (after one second) and waiting for the user to release the button.
So... The states remain the same even for the serial input, you just have to trigger the transitions in another way. The only problem is that the serial input is not continuous, so you have to determine what you mean by "stop sending". In my opinion, you can just set a timeout. The simplest way to achieve this is with this code, IMHO:
const byte ledPin = 13;
const char cmdChar = 'x';

const int onTimeMs = 1000; // The time the led should be on
const int timeoutCmdChar = 50; // The time the char should be off

// In this state the board waits
// for the user input
#define STATE_WAITING 0
// In this state the character was
// received (so the led is on)
#define STATE_RECEIVED 1
// In this state the board is waiting
// for the char to be absent
#define STATE_WAITABS 2

byte currState;
unsigned long recvTime;

unsigned long lastTimeCmdChar;

void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
    currState = STATE_WAITING;
}

void loop() {
    bool cmdCharReceived = false;
    while (Serial.available())
    {
        if (Serial.read() == cmdChar)
        { // Received the character
            cmdCharReceived = true;
            lastTimeCmdChar = millis();
        }
    }

    switch (currState)
    {
    case STATE_WAITING:
        if (cmdCharReceived)
        {
            digitalWrite(ledPin, HIGH);
            recvTime = millis();
            currState = STATE_RECEIVED;
        }
        break;
    case STATE_RECEIVED:
        if ((millis() - recvTime) > onTimeMs)
        {
            digitalWrite(ledPin, LOW);
            currState = STATE_WAITABS;
        }
        break;
    case STATE_WAITABS:
        if ((millis() - lastTimeCmdChar) > timeoutCmdChar)
            currState = STATE_WAITING;
        break;
    }
}

you want something along the lines:
bool continuing;
#define trigger 't'
void loop(){
  if( Serial.avaiable()) {
    char c;
    c=Serial.read();
    if (continuing) {
       if (c==trigger) { //do nothing, ignore it
       } else {
       continuing=False; }
   } else {
     continuing=True;
     motors.start();
     the_time=milis();
   }
 };
 if (the_time+timespan>milis()) {motors.stop();};
}


text:
Bluetooth data: how to handle these data?
I'm reading a BLE device and my api return me this struct
typedef struct {
  LGATTAddress bd_addr;
  int32_t rssi;
  uint8_t eir_len;
  uint8_t eir[256];
} LGATTDeviceInfo;

I try to print some eir_len and eir[256] and this is the result
  for(int i = 0; i < 255; i++)
  {
    Serial.print(info.eir[i], HEX);
  }
  Serial.println();

  Serial.print("Advertising data lenght: ");
  Serial.print(info.eir_len);
  Serial.println();

    21613FF4C0CE8E1B87D83CB43431A739F4496E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    Advertising data lenght: 23

    2167FF4C0102B00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    Advertising data lenght: 11

    216320A0109524543414D3532474A5830313235315125005002A0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    Advertising data lenght: 33

I cannot understand the relation between the air and the lenght: in the second example the response is 13 char but the lenght is 11. Why?
According to bluetooth specs..
The data is 240 octets and consists of a significant part and a non-significant part. The significant part contains a sequence of data structures. Each data structure shall have a length field of one octet, which contains the Length value, and a data field of Length octets. The first n octets of the data field contain the extended inquiry response (EIR) data type. The content of the remaining Length - n octets in the data field depends on the value of the EIR data type and is called the EIR data. The non-significant part extends the extended inquiry response to 240 octets and shall contain all-zero octets.

How can I parse the eir to obtain all the data? For example the name of the device and the manufacturer data?
update
Let's take for example this response
[LGATTC ino]dev address : [8:46:be:ca:2c:2] rssi [-63]
2 1 6 9 8 69 53 65 6E 73 6F 72 20 9 FF BE CA 2C 2 46 2 5F 5D 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Advertising data lenght: 23

I try to convert the hex to string and this part 69 53 65 6E 73 6F 72 is the sensor name (iSensor).
This is a bluetooth sensor that change in this way
<be ca 2c 02 46 02 58 56> - > open
<be ca 2c 02 46 00 59 55> - > close
<be ca 2c 02 46 02 5a 58> - > open
<be ca 2c 02 46 00 5b 57> - > close
<be ca 2c 02 46 02 5c 5a> - > open
<be ca 2c 02 46 00 5d 59> - > close
<be ca 2c 02 46 02 5e 5c> - > open
<be ca 2c 02 46 00 5f 5b> - > close

These are the manufacturer data: the first part be ca 2c 02 is the unique identifier of the device, the 02/00 identify the status of the sensor...
By the way I negin to understand... I notice now the match between the lenght and the eir!
I must now extract the name in char, the status and the device code!
edit 2
I found the specs of my sensors...

Please show your code which is doing the printing.

@MarkSmith added!

Could you indicate what format you'd like this processed into, please?

Just the name is char and the manufacturer data

Do you know how arrays work in C(++)? And do you have a spec, please? I can show you code which works for this example, but with only one example I have no way to generalise it.

A little. But I'm a ruby developer and I'm studying C(++) for this project. By the way all the sensors are from the same manufacturer, and I will use a config file with the unique identifier of the sensors to filter the scanned devices...

OK, I've added code to decode the data. Rather than copying-and-pasting it, better to try to understand what it does and how it does it, and use it to write your own, because I've made VERY big assumptions which are probably not all correct.

I cannot understand the relation between the air and the lenght: in the second example the response is 13 char but the lenght is 11. Why?

The hex numbers may be one or two digits long.  The way the values are being printed does not enable you to discern between 1 2 3, 12 3 and 1 23. Try this:
for(int i = 0; i < 255; i++)
{
  Serial.print(info.eir[i], HEX);
  Serial.print(" ");
}

(Someone already told you this.)

How can I parse the eir to obtain all the data? For example the name of the device and the manufacturer data?

This works for the only example of the data you have given.  If I have guessed correctly how further data will follow, it'll work for them too.  (If I haven't, it won't.)  I have assumed that the name always starts in the same place, ends with a space, three bytes of stuff we don't care about, and that the data is groups of 8 bytes.  It's very likely that some of the other bytes give details of the data to follow, but with only one example and no spec, it's basically impossible to tell.
// Let's assume the sensor name always starts at element 5...
char *sensorName = &(info.eir[5]);
// ...and ends on a 0x20 (space) - which is probably a risky assumption
char *end = strchr(sensorName, ' ');
if (end)
{
    *end = '\0';
    // Sensor name is now in sensorName

    // Let's assume the data starts exactly 4 bytes after the end of the name
    uint8_t *dataItemStart = (uint8_t*)(end + 3);
    uint8_t *dataEnd = info.eir + info.eir_len - 1;
    while(dataItemStart < dataEnd)
    {
        // We have a data item here, as 'dataItemStart'.
        // You can get bytes within it using, for example
        //   dataItemStart[5]
        // to get the 6th item (the 00 or 02 in your examples)

        // Each data item is 8 bytes long, so the next one starts 8 bytes later
        dataItemStart += 8;
    }
}

thank you, I notie now the Paul response! I begin to understand... I add the data I know from a sensor I know!

Thank you so much. I also find the specs of the sensors (I edited the question). I understand that I have 0x08 and then the name (with the space at the end) and 0xFF and then the data. I will try to adapt the code.

That makes much more sense now, with the spec. All the concepts you need should be there in the code above, though.  Feel free to accept and optionally upvote the answer if it helped :-)


text:
Not understanding C++ arrays
I'm attempting to re-write a library for the CD74HC4067 multiplexer.  There is a library available for this device on the Arduino Playground, however, it's limited in its functionality.
I have this as a private data member in the class header file:
uint8_t channelSelects[16][4];

And this in the class constructor:
CD74HC4067::channelSelects[16][4] = {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
};

And I'm getting this error:
cannot convert '<brace-enclosed initializer list>' to 'uint8_t {aka unsigned char}'

Could someone please explain what I'm not understanding here ?
Many thanks in advance.

Are you sure that brace enclosed initializer list can be used in normal assigment beyond variable/const init ?

Actually, no I'm not.  The only difference I see here is the library available on the Arduino Playground has the channel selects defined as external (extern) and defined outside the class.

Aha, the channel select is static init ? So add type:
uint8_t CD74HC4067::channelSelects[16][4] = { .... };

If you have in your constructor this:
CD74HC4067::channelSelects[16][4] = ...

then you are trying to assign something into the element at position [16][4]. Thats why it's telling you

cannot convert '' to 'uint8_t {aka
  unsigned char}'

Anyway - you don't even need that second dimension. You can use binary representation like  0b00001000 ...
And if you'll think about previous line, you don't even need any array, you can do it with simple counter value and getting its bits.
However if you want to rely on this array, the constructor should look like:
CD74HC4067::CD74HC4067() :
  channelSelects {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
  }
{
   // constructor code
}

(maybe one more {} enclosure, I'm not sure right now exactly)
EDIT: I'd go this way (if you need only one or two instances):
// ADC READ channel + Address selection pins
template <uint8_t ADC_Chan, uint8_t Addr0, uint8_t Addr1, uint8_t Addr2, uint8_t Addr3>
class Mux16b {
public:
  void initPins () {
    pinMode(Addr0, OUTPUT);
    pinMode(Addr1, OUTPUT);
    pinMode(Addr2, OUTPUT);
    pinMode(Addr3, OUTPUT);
    pinMode(ADC_Chan, INPUT);
  }

  int readMux(uint8_t channel) {
    digitalWrite(Addr0, channel&1 != 0);
    digitalWrite(Addr1, channel&2 != 0);
    digitalWrite(Addr2, channel&4 != 0);
    digitalWrite(Addr3, channel&8 != 0);
    // maybe some delay to stabilize voltage at the ADC_Chan input ??
    return analogRead(ADC_Chan);
  }

  // not necessary but it's easier to use   mux(10) than mux.readMux(10)
  int operator()(uint8_t channel) { return readMux(channel); }
};

// analogRead from A0, Address pins: 4 9 5 2
Mux16b<A0,4,9,5,2>  mux;

void setup() {
  Serial.begin(115200);
  mux.initPins();
}

void loop() {
  Serial.println(mux.readMux(15));

  Serial.println(mux(12)); // using overloaded operator ()

  delay(5000);
}

Thank you, KIIV.  However, this initialization is based on the original library for the device as well as an example at http://bildr.org/2011/02/cd74hc4067-arduino/.  There are 4 separate control pins the device needs to connect to on the Arduino, hence the second dimension of the array.

In the example there is declaration and initialization at once. In the class you have declaration in the class and initialization later. In the definition brackets means size (number of elements). Anywhere else it means accessing element at passed position (index)

Thanks again, KIIV.  I somewhat understand.  I moved the initialization to the header file where it was first declared, then got undefined reference for the destructor.  I commented-out the destructor in the header file and it compiled without errors.  Not real sure I like the destructor being commented-out, though.

Concerning my last comment, I was missing the destructor in the .cpp file.  I added it, and it compiled without errors.

@GregoryR.Pace I can imagine that code without any variable just by using template class. It's perfect if you have one instance (or two). For more instances with different template parameters it might take more code space.

I moved the initialization to the header file where it was first declared...  It compiled without errors.

You may just print out the array as well, compiling w/o errors doesn't neccesarily mean it does exactly what you think it does ;p Also, the values in your array are 4-bit LSB representations of the integers 0to15, you can store this much more efficiently or calculatie it runtime. Or consider using an array of objects/(bit-)structs instead of an array of arrays of unsigned chars, only to represent bools.

You need , at the channel 15 line too.

Thank you, Andreas.  I just added the comma, but still getting the same error.

That last comma is optional.


text:
Newbie Arduino DC motor problem
So I am new to Arduino and new to electronics in general. I've looked up a few tutorials and they all have a simple early tutorial that turns on a DC motor and turns it off again. Something like this:

(source: cloudfront.net)
The transistor I am using is a 2N2222 and the motor is a little 3V DC toy motor.
The problem is that the when I use this circuit, the motor barely turns (I need to give it a little help to get it it moving). I know my code is right (motor is on for 5 seconds, off for 1). i can tell this is working but clearly something is not right.
I am powering the Arduino off the USB port.
As a test, I swapped out the 2.2K Ohm resistor for a 560 Ohm resistor and the motor seems to run fine. However, it creeps during the "off" time (the motor is not under any load). Also, the transistor gets very hot after about a minute of running this loop.
So my questions are:

Why does the motor not work when I use the 2.2K Ohm resistor when I see that 2.2K Ohm resistor in different circuit diagrams that demonstrate this type of circuit?

Why does changing to the 560 Ohm have the effect that it does

Why does the motor creep during the off cycle when using the 560 Ohm?

Why does the transistor get so hot using the 560 Ohm resistor?

Finally, sometimes as a test, to simple try to turn turn the motor on, I will just reroute to pin 9 wire directly to the Arduino 5V on my breadboard (bypassing Arduino control altogether). Is there any reason this is a bad idea?

I am anticipating questions about current draw but my multimeter maxes out at 200mA; I am getting a new one that goes to 10A and will help me see how much I am drawing.
Thanks in advance of any help. I have tried to be clear and concise so hopefully this does not elicit any snark. If there are any resources to point me to, I would be happy to hear them.
Thank you!
Jim

Are you using external power source? USB is not strong enough for driving DC motor.

Are you sure you have wired the transistor the right way round?

The transistor is a current driven device. When it is saturated the CE voltage should be around 0.7V, if more as you will see with the 2.2K you are not driving it hard enough, something in the 200 Ohm range should work nicely although the 560 might depending on the transistor gain. Try using a voltage driven device with the same circuit with a Logic Level avalanche rated N-Channel MOSFET (C-D, E=S, B=G) rated at a few amp. With the avalanche rated MOSFET you can leave the diode off. Expect much better performanced and a lot cooler part. The MOSFET will be cold  it is not burning power as heat.

I see a couple of issues here, which are related to your questions. I will use numbers here, but these do not necessarily correspond to the numbers you have used when asking.

The first thing you need to do when controlling a motor is to know it maximum stall current. The stall current is the current that will circulate through the motor (and through the transistor) when you apply an external force to stop the motor's shaft. But it's also the same current needed for the motor to start when it's completely stopped. So, for dimentioning a transistor, you typically will select one that has, as a rule of thumb, a collector current two times bigger than the motor's stall current.
The 2N2222 has a maximum Ic of 800 mA (best case, since there are 600 mA versions as far as I know). Although you are not specifying much about your particular motor, a typical 3V DC motor may easily be asking for 500+ mA. Some small motors (specially bad quality ones) may have stall currents bigger than 1 A.
If your motor is asking for, let's say 300 mA when continuously running, then, you are near enough of the maximum current of the 2N2222.
But there is something more important here: dropout voltage in the transistor. The 2N2222 is a bipolar one, so it will have a Vce superior to 1V (probably around 2V), which means that you are dissipating a non trivial amount of power in the transistor. That power is not useful for your motor, nor for your transistor. Here, if the motor has a 3V nominal voltage, the 2V dropout in the transistor is even desirable, but I don't see your calculations about the real dropout in your description. So I assume that you are just counting that there will be an approximate 2V dropout. That means that, if your motor is taking 0.5A to work, you are dissipating 2V x 0.5A = 1W (Watt) in the transistor. But the poor 2N2222 is a 0.5W transistor! But even if your motor is using much less current, let's say 0.25 A, you are sill using it at its limits. That will explain why it's getting hot.
So, my advice is to go for a bigger transistor, if you want to count on its dropout to do not apply a voltage bigger than 3V to the motor (which can really reduce it lifespan a lot), AND do some calculations to be sure that at the currents you are using, you will have the Vce that you want.
Another option, probably better, is to replace that bipolar old transistor by a MOSFET, but you will need to provide the apropiate voltage for supplying the motor, since if not you will get nearly all the 5V to the motor (due to the very low Ron on Mosfets, and thus very low dropout voltage), and that will be very bad.
Also, please note that the 500mA of the USB port are probably not enough for your setup. But even if you are powering your Arduino from an external power supply through its power jack, you will find a good idea to use common grounds but different Vcc sources for logic and for the motor.
Finally a short advice: be sure that the diode protecting the back EMF (the diode connected with its cathode to Vcc in your circuit) is a fast diode. A slow, 1Nxxxx diode is usually to slow for effectively protecting your transistor. If you are using for example an 1N4007, you can switch to a UF4007 (Ultra Fast).
Regarding your 560R vs 2K2 resistor, this exceeds the answer a bit, so my advice is to read something about base resistors in transistors, like this. Also something about open collector configurations may help.
Finally, the practice of connecting the base resistor to Vcc in this kind of circuit to test the transistor should be fine. But DO NOT CONNECT the transistor's base directly, use always the resistor.

The links to the evilmadscientist alone is worth a +1, but very nice answer. I have the same issue with a sample Arduino kit and a motor that stalls at start so now I know how to approach it.

***ERROR CORRECTION: Sorry all, I did have one error in my code that explains the creep. I thought I was running a loop to simply turn the motor on and off but actually it was running full on for 5 sec (255) and partial speed (120) of 1 sec, thus the creep. When resetting the code to on on for 5 sec, fully off for 1 sec, with a 560 Ohm resistor, things work as expected. (I still have the problem with the 2.2K Ohm though so most of my question stands.
nbloqs, Thank you ; I will review your answer in detail.
What would so many tutorials show this basic schematic if to has so many issues?
Thanks again!

Some of the tutorials are designed for kits that come with motors where they know the currents involved. Also, usually they are pretty basic and most of them will not deal with base resistor values, or proper transistor selection. I was not saying that the 2N2222 will not work, but it will probably operate at its limits and thus will be heating (specially if the motor is kind of unknown). Regarding your resistor, I added point 9 to my answer.

Also added point 10 about your "test with Vcc" question.

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


text:
Why am i getting "phantom" readings from a flowmeter?
I have 2 flowmeters hooked up to my arduino uno.  They're set to read beer volume as beer flows through them.  Everything is working great, except i'm getting phantom readings.  I have the arduino communicating w/ a raspberry pi over USB, and i set my python script on the pi to start logging when reads are taking place.  i'm getting reads of 1-3ml every 15-30 mins (with 1 fluke of 16ml).  i have 2 flowmeters connected, but only 1 is sending these pulses.
there is nothing coming out of the taps, and everything inside the kegerator is bone dry.  i don't know what to look for...

As is, this looks too vague to be answered.  Please edit your question to at least give  the model numbers of flowmeters.  Presumably they can jitter and/or lack hysteresis?  If the problem may be in code, then include a Minimal, Complete, and Verifiable example of code that exhibits the problem

Try swapping the meters, and see if the problem is with the meter (or keg), or the rest of the system.

It could be a dodgy earth connection.


text:
Reading PushButton status with pyserial
I'm trying to read the status of a PushButton with python via pyserial.
In the loop function of Arduino Uno I have this:
void loop() {

if(digitalRead(BUTTON) == HIGH){
Serial.print("E\n");
while(1){}
}

So, if my pushbutton is pressed, it will send this message "E" via serial and then it will enter in an infinite loop so that nothing else happens.
But I want to detect this message in the python code. So this is my python code:
import serial
import time

try:
   arduino = serial.Serial('/dev/ttyACM0', 9600)
except:
   print "Failed to connect on /dev/ttyACM0"

try:
   print arduino.readline()

   while True:
      if arduino.readline() == 'E':
        print("Detected!\n")

except:
   print ("Failed to read!")

The first print before the infinite While is working: it is printing in the ubuntu terminal "Program Initiated", which is a message that I'm sending in the void Setup function of Arduino.
Then, it gets stucked in the line:
 if arduino.readline() == 'E':

I mean, I press several times my pushbutton, and nothing is happening.
Any help?
Thanks!

Use arduino.read instead of arduino.readline

Isn't more secure to use readline() once I will end up my message with \n?

The string you are sending ("E\n") is not the same one you are checking for: 'E'.
You could, for example, strip newlines from the string:
if arduino.readline().strip() == 'E':

You're right! I thought that as I was using .readline (which stops reading with \n) it wouldn't be necessary to put it on. Thanks, now it's working - without using that strip thing. What does it do exactly?

strip() removes newlines and whitespace from the start and end of strings. I'm slightly surprised that readline() works at all if you're not sending newlines but OK if it does. Please feel free to accept the answer if it was helpful.


text:
Is this example for playing music without delay correct?
I've followed the directions from this answer, to try and play music without delay. This is my code so far:
#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

const int tonePin = 4;
unsigned long previousMillis = 0;
int counter = 0;
int numberOfNotes = sizeof(melody)/sizeof(int);
boolean outputTone = false;

void setup() {
  pinMode(tonePin, OUTPUT);
  //Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();
  unsigned long noteDuration = 1000 / noteDurations[counter];
  unsigned long pauseBetweenNotes = noteDuration * 1.30;

  if (counter < numberOfNotes) {
    if (outputTone && ((currentMillis - previousMillis) >= noteDuration)) {
        previousMillis = currentMillis;
        noTone(tonePin);
        outputTone = false;
        counter++;
    }
    else {
        if ((currentMillis - previousMillis) >= pauseBetweenNotes) {
        previousMillis = currentMillis;
        Serial.println(melody[counter]);

        if (melody[counter] == 0) {
          noTone(tonePin);
        } else {
          tone(tonePin, melody[counter]);
        }

        outputTone = true;
      }
    }
  }
}

pitches.h can be found here.
So with this code, the music plays, but slower. The pauses between notes seem longer, and I can't figure out why.
Also, I'm not sure where should I increment my notes counter.

In this code, your pauseBetweenNotes is *in addition to * the duration of the note. In your previous code, IIRC, it included the duration of the note.
Change it to 0.3 times and I think it will behave as you expect.

This is the example. If I understand correctly, a note is played for the duration of noteDuration, and then there is a silence for pauseBetweenNotes, and so on, and that, noteDuration + pauseBetweenNotes is the full duration of one note? But pauseBetweenNotes is still a full note duration + 30%? (There is no need for the noTone function then right?).

I've never used this pitches library, but it looks like tone() returns immediately, and the note carries on playing in the background.  In the linked example, the tone will start playing and the code will continue.  It immediately sleeps for 1.3x the length of the note - so the note will finish and then we'll still have 0.3x the length to sleep.  Does that make sense?  In your code above, we wait for the length of the note, and THEN sleep for 1.3x the length of the note.

There's a variable called "pauseBetweenNotes". Try modifying that and see if the pause between notes becomes smaller.
Regarding your counter question, the way the counter is set up looks fine to me.


text:
Need clarification with arduino syntax
I've been learning how to program this fine piece of equipment but i seem stuck. I came upon the "Knight rider" example where you are supposed to blink LED's from one side to another and i can't understand where some of the code comes from. For example:
byte ledPin[] = {4,5,6,7,8,9,10,11,12,13};
int ledDelay;
int direction = 1;
int currentLED  = 0;
unsigned long changeTime;
int pot = 2;
int i;

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

    for (i = 0; i < 10; i++)
    {
        pinMode(ledPin[i], OUTPUT);
    }

    changeTime = millis();
}

void loop()
{
    ledDelay = analogRead(pot);

    if ((millis()- changeTime) > ledDelay)
    {
        changeLED();
        changeTime = millis();
    }
}

void changeLED()
{
    for (i = 0; i < 10; i++)
    {
        digitalWrite(ledPin[i], LOW);
        Serial.print("i = ");
        Serial.println(i);
    }

    digitalWrite(ledPin[currentLED], HIGH);

    currentLED += direction;

    if (currentLED == 9)
    {
        direction = -1;
    }

    if (currentLED == 0)
    {
        direction = 1;
    }
}

In this code I don't  know where the "direction" variable is coming from I searched on the arduino reference page but can't find it. Are there other references where I could look or am I misunderstanding something?

It's coming from the program itself:
int direction = 1;

That means "Create a signed integer called 'direction' and assign it the value 1.

You defined the direction variable on the top with:
int direction = 1;

Yes I am fully aware of that. But in the sketch it is coloured red, if i rename it to "dir_etc" for example it is not highlighted by the IDE.  So i'm sure there is more to it than just me defining it. Hope my explanation is clear enoght.

Hm, that's interesting. What IDE are you using? It could be defined as a global variable in one of the files that you are including, but that sounds very unlikely to me. What files are you including in your project? Also (depending on your IDE) you might be able to right click on the variable and chose "View variable declaration" or something like that.

I'm using the official IDE v1.8.1 from the arduino site. Other than that i don't know to be using  any files for this sketch, but then again I'm just a beginner so i might be wrong. Also i can't find the "View variable declaration" you're  writing about.

Ok, so we ruled out a couple of things. I'm using the same IDE, but I haven't had a similar thing happen to me. Can you post a screenshot of how the code looks like (how the direction variable is colored)? And post the error message you receive?

Hope these images are clear enough   http://imageshack.com/a/img922/9182/9xd84Z.png http://imageshack.com/a/img923/8880/Fdx0x9.png

And i don't have any errors actually the sketch is running just fine I'm just trying to understand how the code works in order to modify it and it seemed strange that "direction" is highlighted red and i can't find it on the reference page.  Sorry for double post.

Aaa nice, the mystery is solved. All that means is some library author decided direction was a keyword (which is a horrible idea in my opinion). Searching and greping on my system says that this is person to blame: ./arduino/arduino-1.6.12/libraries/Stepper/keywords.txt (I don't know what system you run, but it should be in a similar hierarchy where you have Arduino IDE installed).

This however is not a problem for you (except that it's highlighted). When you define a direction variable in your code your variable will be used because of how variable scope works. This is not a language keyword, you can't define a variable named int (you might know all of this, if so sorry). So that's it :) I'll provide more links in a new comment. Feel free to ask more.

You can make your own keywords when writing a library so they are highlighted in the IDE (and only there) to make things nicer, an in your case someone decided to make the word direction a keyword in their library :)

Simple explanation of your case

A bit more complex explanation

Really detailed technical explanation

As I said feel free to ask more, and thanks, I learned something myself today! :)

Marvelous! Thanks for the help and sorry for the late reply.


text:
Why does my LCD screen display white rectangles?
I recently got an Arduino LCD screen. I tried connecting it to the UNO with the 10k potentiometer and all the needed equipment but all I got were white rectangles instead of characters. I have uploaded the hello world code but I saw no changes.

Looks like you may have the contrast set (or wired) wrong.

Or you have drawn white rectangles to the screen.

As @Majenko already mentioned, you have to set the right contrast. Use potentiometer to find out what value suits you right.


text:
Using analog in to read a push button
I'm working on a project in which I use a lot of the pins on the Arduino;  I have run out of most of the pins and and I need to read the value of a push button.
Is it possible to read the value of the switch in the analog in pins on the board??
If so how can I implement this?

Is it possible to read the value of the switch in the analog in pins on the board??

Yes. Analog input pins are also digital IO pins. You can use them exactly the same way as all the other pins on the board.

e.g. digitalRead(A1)

On ATmega640/ATmega1280/ATmega1281/ATmega2560/ATmega2561 devices (with Arduino Mega using an ATmega640 or 2560), the analog input pins have their analog capabilities in addition to standard digital capabilities.  They can be used to read or write digital values, like other digital pins on the device.
On ATmega48A/PA/88A/PA/168A/PA/328/P devices (with Arduino Uno using an ATmega168- or 328-family device) analog inputs A0 ... A5 have standard digital capabilities, but A6 and A7 do not.  A6 and A7 on an Uno or Nano is limited to analog input.  However, you can use a circuit like the following to multiplex several buttons.  With this circuit attached to A6,  you would get 1 V at A6 when you press S1; 2 V when you press S2; 3 V when you press S3; and so forth.  You get 0 V at A6 when all the switches are open.

One would first use a fast analog read (about 13 μs) to decide if any switch is pressed; for example, if the first reading is above 1/2 V.  In some systems, a fast reading may be good enough by itself to decode switch number; if not, take a second reading via ordinary analog read.  In any case, given an analog reading ar, and letting CPS be the expected step in counts from one switch to the next (in this case either 256/5 or 1024/5 depending upon use of 8 or 10 bits of readings), compute switch number via something like s = (ar+CPS/2)/CPS;.

Same things happens with me.
Here, it's my code. It's works for me.
const int kPinBtn = A0;  // Push-Button connected to Analog pin A0
const int kPinLED = 13;  // LED connected to to Digital Pin 13

void setup()
{
  pinMode(kPinBtn, OUTPUT); // Generally, in push-button we take INPUT as a parameter but here we take OUTPUT because ANALOG PIN

  digitalWrite(kPinBtn, HIGH); // Make button condition HIGH

  pinMode(kPinLED, OUPUT);
}

void loop()
{
  // Now, normal push-button operation, LED blink when we press push button

  if(digitalRead(kPinBtn) == LOW)  // If button pressed
  {
    digitalWrite(kPinLED, HIGH);   // Blink LED
  }
  else digitalWrite(kPinLED, LOW); // Else LED is off
}

Is it possible to read the value of the switch in the analog in pins
  on the board??

As other answers say, you can use digitalRead on most Analogue pins.  But to answer the question, yes you can read analogue input, which is useful on pins like A6/A7 which cannot be used as digital pins.
You should connect the pin with a pull up resistor - for arduino pins A0-A5 (depending on board, i'm referring to a Nano) this can be done internally using:
pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5

If you are working on pins A6/A7 you cannot access the internal pull-up resistor, so you need to add your own to prevent a floating input.  A 10K resistor should go between the input pin and VCC.
Lastly, an example of reading the input:
const int buttonPin = A7;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

void loop() {
  // read the state of the pushbutton value:
  buttonState = analogRead(buttonPin);

  Serial.println(buttonState);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState > 512) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

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


text:
How to program an Arduino Uno Pro with a makefile?
I'm using Arduino Makefile to compile sketches for Uno and Mega boards. I'm now trying to compile a sketch for an Arduino Uno Pro, which is an Uno with a replaced chip to give it features more like a Mega.
When writing a makefile to compile for this board, which BOARD_TAG should I use? I don't see this board listed in the official Arduino or Arduino Makefile docs.

After you edit your boards.txt file to incorporate the Arduino Uno Pro section from near the end of that Arduino Uno Pro webpage at hobbytronics.co.uk that you referenced, the board tag list produced by make show_boards will include the following line:
uno_pro       Arduino Uno*Pro

indicating the tag should be uno_pro.

I also had to copy over a pins_arduino.h file, but yeah, that was it. I thought it required something more the makefile.

@Cerin, glad you got it to work ... I've been impressed by the documentation quality and the ease of use of this particular Arduino Makefile system.  BTW, if copying the pins_arduino.h file fixed the other problem you posted, you probably could either delete that question or answer it.


text:
Arduino Due connection with FLIR Lepton
I'm trying to connect a FLIR Lepton to an Arduino Due. A thread by pureengineering talks of rerouting some pins. I am not sure what they precisely mean.

Does this rerouting mentioned in the link also apply to Arduino Due?

According to the highlighted part of Due schematics it'd be better to connect 3.3V to the AREF pin as there might be some significantly big resistor between AREF and 3.3V source. So it might not be needed but one never knows.
Edit: Looking at the DUE board, there is "jumper" resistor, so you can choose 3V3 or AREF, that means AREF is not connected to anything by default. So if you connect 3v3 to AREF, it should be fine (even 5V, if you didn't changed anything on board yet
)


text:
Demultiplexing Arduino with C++ code
I have been working on a small project recently. I have a circuit like in the image below:

Hardware Setup Demultiplexer IR Test

As you can see I have 8 IR LEDs, which are driven by an MC14051B Multiplexer/Demultiplexer. My goal is to select each IR led individually and send data over the selected IR LED. None of the other LEDs can send signals. Only one LED at a time can be sending IR codes.

Hardware Setup Single IR Test

Below is the code I used to send the signal using the IR Library over one LED (no demultiplexer was used in this test).
// New function to send 'items' codes which are held in the array 'data'
void sendMulti (const uint8_t& items, const uint32_t* data) {
  for (int i = 0; i < 2; i++) {
    for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex) {
      irsend.sendNEC(data[itemIndex], 32);
      delay(1000);
    }
  }
  delay(5000); //5 second delay between each signal burst
}

void loop () {
  static const uint8_t MaxItems = 3;
  uint32_t  data[MaxItems] = {0x1067E21D,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x106722DD,0x10676897,0x10676897,0x10676897,0x10676897,0x10676897,0x10676897,0x10678877,0x10676897,0x1067A857,0x1067A857,0x10678877,0x1067A857};
  sendMulti(MaxItems, data);
}

The Single IR Test was a success. However now I want to use the demultiplexer. Any advice or pointers will make me very happy.

Explain the usage of pin A0.

The most important document you have to read is called a datasheet. Here you can find the MC14051's.
I assume you already know how a mux/demux work, so... Well, you have eight LEDs, one on X0, another on X1, ... up to X7. The one connected to the pin X, which is your A0 (the pin used on irsend, I assume) is indexed by the three inputs A, B and C.
On page 5 you see the truth table. According to that table, you have to write a 0 on inhibit, and the value on ABC. So, to select led on X0, you have to write 0 on pins 7, 8, 9 and 10. If you want to select led X1, 8 should go high. For led X7, 8, 9 and 10 should be 1, while 7 is low. And this is for all the combinations...


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

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

float MAP;

float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

float LOAD_MIN_MAP_MIN = 2.00;
float LOAD_MAX_MAP_MIN = 15.00;

float LOAD_MIN_MAP_MAX = 10.00;
float LOAD_MAX_MAP_MAX = 85.00;

float mMAPmin;
float mMAPmax;

float yMAPmin;
float yMAPmax;

float mMAP;

float yMAP;

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

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

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

float TPS;

float TPS_MIN = 0.00;
float TPS_MAX = 5.00;

float LOAD_MIN_TPS_MIN = 2.00;
float LOAD_MAX_TPS_MIN = 10.00;

float LOAD_MIN_TPS_MAX = 15.00;
float LOAD_MAX_TPS_MAX = 85.00;

float mTPSmin;
float mTPSmax;

float yTPSmin;
float yTPSmax;

float mTPS;

float yTPS;

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

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

int LOAD_MIN = 2;
int LOAD_MAX = 100;

float injTime_MIN_LOAD_MIN = 4.00;
float injTime_MAX_LOAD_MIN = 4.60;

float injTime_MIN_LOAD_MAX = 8.06;
float injTime_MAX_LOAD_MAX = 14.86;

float LOAD;

float mLOADmin;
float mLOADmax;

float yLOADmin;
float yLOADmax;

float mLOAD;

float yLOAD;

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

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

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

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

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

int RPM_MIN = 400;
int RPM_MAX = 6000;

float injTime_MIN_RPM_MIN = 4.00;
float injTime_MAX_RPM_MIN = 8.06;

float injTime_MIN_RPM_MAX = 4.60;
float injTime_MAX_RPM_MAX = 14.86;

float mRPMmin;
float mRPMmax;

float yRPMmin;
float yRPMmax;

float mRPM;

float yRPM;

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

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

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

float minPosVolGas = 0.00;
float maxPosVolGas = 2.50;

float minInjPerPos = 0.35;
float maxInjPerPos = 0.00;

float minNagVolGas = 2.50;
float maxNagVolGas = 5.00;

float minInjPerNag = 0.00;
float maxInjPerNag = 0.25;

float mGasPos, mGasNag;
float yGasPos, yGasNag;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

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

void countRPM()
{
  RPMpulses++;

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

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

After suggestion of Majenko and some modification(done by me) my updated code working fine. My relay operate very well. My OUTPUT Pin 13 Square Wave synchronized with INPUT Pin 2 Square Wave Here is my updated code :
//----------------------------For MAP calculation----------------------------//
float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

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

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

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

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

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

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

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

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

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

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

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

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

int RPM_MIN = 400;
int RPM_MAX = 6000;

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

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

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

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

float minInjPerPos = 0.35;
float maxInjPerPos = 0.00;

float minNagVolGas = 2.50;
float maxNagVolGas = 5.00;

float minInjPerNag = 0.00;
float maxInjPerNag = 0.25;

float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

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

const int kPinInj = 13;

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

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

  pinMode(kPinInj, OUTPUT);
}

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

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

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

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

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

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

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

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

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

  LOAD = (yFinalTPS + yFinalMAP) / 2;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

void countRPM()
{
  RPMpulses++;

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

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

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

Now, I want to see my all readings on serial monitor, so for that, I used Serial.print() line. But, now one problem is appeared. Because of this line, my OUTPUT Pin 13 Waveform not synchronized with INPUT Pin 2 Waveform:
Below my code after adding Serial.print() in my code to display readings on serial monitor. You can see bunch of lines of Serial.print() at the end of the code :
//----------------------------For MAP calculation----------------------------//
float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

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

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

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

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

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

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

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

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

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

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

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

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

int RPM_MIN = 400;
int RPM_MAX = 6000;

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

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

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

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

float minInjPerPos = 0.35;
float maxInjPerPos = 0.00;

float minNagVolGas = 2.50;
float maxNagVolGas = 5.00;

float minInjPerNag = 0.00;
float maxInjPerNag = 0.25;

float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

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

const int kPinInj = 13;

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

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

  pinMode(kPinInj, OUTPUT);
}

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

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

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

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

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

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

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

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

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

  LOAD = (yFinalTPS + yFinalMAP) / 2;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

void countRPM()
{
  RPMpulses++;

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

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

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

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

Finally, problem solved. Just keep maximum baud rate.

Here is how I would do it:
volatile uint32_t injTime = 0;

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

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

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

Basically, when the interrupt triggers you remember when it triggered and turn on the relay.
Then in your main loop, if the interrupt has been triggered, and 10 milliseconds have elapsed since the interrupt was triggered, then forget that the interrupt was triggered (so you can see the next one) then turn the relay off.
The key point is that you remember when the interrupt triggered, and count your time from that point onwards.

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

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

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

I don't know that things.

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

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

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

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

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

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


text:
How I Can Send the status of switch in SMS by Arduino?
How I want help ,, I want send status of Switch If switch > 20 send SMS status of switch OFF and when switch <20 than mean switch ON , Don't want send the value of reading.
I use Arduino uno
If I want use multiple switch and send all status of switchs in one message.
I mean if switch1 > 20 ON and switch2 <20
I want send status of switch In one SMS
Switch1 ON
Switch2 OFF
Switch3 OFF
How I can do this??
void loop()
Switch = analogRead(S_Switch);
if (Switch > 20 )
{
Serial.println(Switch);// If Switch > 20 show in SMS switch statuse  OFF,, If switch < 20 show in SMS switch statuse ON
Serial.print("\n******************\n");
Sim900Serial.print("AT+CMGF=1\r"); //Sending the SMS in text mode
delay(1000);
Sim900Serial.println("AT + CMGS = \"+***************\"");//The predefined phone number
delay(1000);
Sim900Serial.println("MY Swicth statuse is :");
Sim900Serial.println(Switch); // I don't want the value of Switch I want ( ON , OFF )
 Sim900Serial.print("              ");
Sim900Serial.println((char)26);//the ASCII code of the ctrl z is 26
delay(5000);
Sim900Serial.println();
}

Do you want to send the value in both cases, ON and OFF?  Do you just want it to keep sending constantly, over and over, or some other behaviour (e.g. when it changes)?  Does your existing code work (but not do what you want)?

Here, Updated Code...
const int switchOneInput = A0; // Switch 1
const int switchTwoInput = A1; // Switch 2

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

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

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

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

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

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

}

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

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

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

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

Thanks dear but still you don't understand me this I can use just for one switch ON or OFF , if more than one switch ,, And I want both status in one SMS

I mean both status Switch1 ON or OFF and Switch2 ON or OFF In same SMS. Example Switch1 ON , Switch2 ON

Ok. Got it. You mean like if Switch 1 is ON or OFF then SMS you notify you about Switch 1 is ON or OFF. And now if you add another Switch let say Switch 2. So, now suppose Switch 1 is ON and Switch 2 is OFF then SMS be like Switch 1 is ON and Switch 2 is OFF. Am I right ?

Thanks Hasan,, Yes and send in one SMS so any change in switch will change in SMS

Ok. Got it. Let me modified my code.

I just modified my code. I hope it will help  you.

Let us continue this discussion in chat.


text:
Accelerometer (I2C) and Fona Shield (software serial) won't work together
I am using a Fona 808 shield with an Arduino Uno and the LSM303 accelerometer. The accelerometer is connected via I2C and the Fona uses software serial.
My project requires the accelerometer to be continuously polled and occasionally talk with the fona. I wrote a program that just used the fona, but once I added the accelerometer code the program would hang a few seconds after comms had been opened with the Fona. I have tested both the accelerometer and the fona shield separately, and they work fine. So, I wrote another smaller (test) program (which is attached below) to find the origin of the program, which I identified to be:
fonaSerial->begin(4800);

fona.begin(*fonaSerial);

After these lines of code are added, the problem arises. As I said before, this is what I see a few seconds after comms have been opened with the Fona.
http://pasteboard.co/A16708fo3.png
My test program reads the value from the accelerometer, calculates the magnitude of the acceleration and if it's over 20, it prints "Over 20", while also initialising Fona serial.
My question is: Why don't the accelerometer (I2C) and the Fona (Serial) work together and how this be fixed?
This is quite urgent so a quick responses are greatly appreciated!
My Code:
#include <Adafruit_FONA.h>
#include <Adafruit_Sensor.h>
#include <My2_Adafruit_LSM303_U.h>
#include <Wire.h>

#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4

#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;

Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

volatile byte accelMagnitude;

Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);

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

    accel.begin();

    Serial.begin(115200);

    fonaSerial->begin(4800);
    fona.begin(*fonaSerial);

}

void ReadAccel(){

//Get a new accelerometer sensor event
  sensors_event_t event;
 // Serial.println(F("Accel---------"));
  accel.getEvent(&event);

  accelMagnitude = sqrt( sq(event.acceleration.x) + sq(event.acceleration.y) + sq(event.acceleration.z));

}

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

    ReadAccel();

    if (accelMagnitude > 20){

        while (accelMagnitude > 20){

            Serial.println("waiting");
            ReadAccel();
        }

        Serial.println("Over 20");

    }
}

Try adding some additional Serial.print commands, so you can see where the programs gets stuck.

The code works fine for about 4 seconds after opening comm with ATs and then it just stops completely.

How do you know that is stops completely? It could be that the accelerometer is returning false data, and that the arduino code is still running fine. That's why I suggested adding additional Serial.println commands. When debugging some code, I sometimes have a Serial.println between every line of code, so I know exactly where the problem occurs.

I added Serial.println("Hello");  into the loop. Hello is printed continuously and then stops after 4 seconds.

Well, there you have narrowed it a bit down. Try adding some more commands and see exactly after which statement is stops. In the mean time try changing sensors_event_t event; to static sensors_event_t event;. I've got a feeling, that maybe there's a memory issue.

I added static but nothing changed. I also added Serial.println("Bye"); into the ReadAccel(); function. The last word it prints is hello (which means the program stops in the ReadAccel() function).

What are you using to power the circuit?

Also, try adding a small delay in the loop, and see if it now takes more than 4 seconds.

I am using a 3.7V Lithium Polymer battery to power the circuit. I first added a 100 ms delay and then a 10 ms delay. The 100 ms delay worked for about a minute. The 10 ms produced the same problem as earlier and once I switched back to the 100 ms delay I again got the same problem as earlier.

I'm out of ideas. Sorry.

I removed the static and tried the delay again. It nows seems to sort of work. Why could this be?

Too little free RAM? Too little power (e.g. the fona connects to the cell-network after 4 seconds, and required a lot of power to transmit)? Something else?

Thank you, Thank you, Thank you, Thank you!!!!! The connection to the cellular network seems to be the problem. I added a 10 sec delay before starting the loop to allow the Fona to connect to the network!

Glad you got it working. But I'd still try and figure out the exact problem if you can. It might come up later, when you try sending a text-message for example. Maybe adding a large capacitor to Vcc.

I have the same problem, I'm not using an accelerometer, but a RGB sensor that works via I2C too. I did come to the same solution of waiting a fair amount of time before initializing the I2C, but after a random amount of time it restarts the arduino.

As Gerben suggests, it would not be a good practice to just add a delay and call it a day.
1) Have a large electrolytic capacitor between Vcc and GND as near as you can to the FONA and
2) FONA has getNetworkStatus(); make a small control loop and query it until you get status 1 or 5, depending on what network are you on.
From FONA's example:
if (n == 0) Serial.println(F("Not registered"));
if (n == 1) Serial.println(F("Registered (home)"));
if (n == 2) Serial.println(F("Not registered (searching)"));
if (n == 3) Serial.println(F("Denied"));
if (n == 4) Serial.println(F("Unknown"));
if (n == 5) Serial.println(F("Registered roaming"));

And then proceed with the rest of your code. You can make additional checks for signal quality with getRSSI();


text:
Serialprint and analogRead time
How much time takes to print each sample using Serial.print and analogRead in each iteration?
#include <SoftwareSerial.h>
#define Sensor A0
void setup() {
  Serial.begin(250000);
  pinMode(Sensor,INPUT);
    }
void loop() {
  Serial.println(analogRead(Sensor));// RUN TIME??
}

It depends on how full the buffer is and how big the value being printed is.

@Majenko The sensor output is between 0 and 100 in serial printing.

It is quite complex to work out how "long" it will take to print.  Why?

If there is room in the serial buffer then the text just gets placed in that buffer. Takes almost no time at all to print.
You are printing a variable length string. The longer the string the longer it will take to print if the buffer is full.

However:

Each character consists of 10 symbols (8 data bits plus 1 start and 1 stop bit).
Characters are transmitted at 250000 symbols per second
Thus each character takes 1/(250000 / 10), or 40 microseconds to transfer through the actual wire.

So printing the number 100, which also has \r\n appended to it (characters 13 and 10) would need 5 characters. If the buffer is full it will take about 5*0.00004s = 200µs. If the buffer isn't full, it will take a fraction of that to just copy the data into the serial buffer.

1000 rounds of analogRead() takes about 100ms.
sustained serial writes will depend mostly on the baud rate picked.

Thanks, do you have a document indicating CPU cycles for different operations?


text:
Make device based on CH340G working as keyboard
There is small board with gyroscope. Controller - Atmega 8a, com-usb chip is CH340G. Board is handmade but not by me so I don't sure is it Arduino clone or not. It works with "ch341ser" driver on the computer and is used in small video game writed on java. This game is ran by .bat file where I specify COM port number, game listen this port in code.
I need to do anything to make computer understand gyro tilt as arrow keyboard buttons commands. In other words I need to write a driver or smth else to make computer understand device as USB HID keyboard. Is it possible to do it programmatically and how to do that?

You could try using V-USB, instead of using the CH340G that only does serial.

It will be a lot easier to buy a Arduino Micro or Pro Micro with a ATmega32U4. That chip can be set as a keyboard with standard Arduino libraries.

No, it's not possible. The device enumerates as a USB serial device, and the only way to change that is to change the internal silicon of the device.
The closest you could do is (though I have no clue how on Windows) write (or if you are lucky, find) a program that reads serial data through the COM port and somehow injects keyboard commands into the input subsystem of the operating system.

@DiA I found this that may help: https://www.232key.com/


text:
Finding and loading "libraries"
I am 6 months into my Arduino Uno work and I would like a step by step way to find and download a "library". I work using WINDOWS and WORD and although I was eventually successful in getting a 7 segment display library to download and work, I must say I could not do it again since the path I followed was far from clear due to my lack of understanding about basic computer stores etc. I have enjoyed my work with the Uno but I have been very disappointed at lots of "help" offered on other sites since they assume I know far too much. It is a skill to be able to communicate with we lesser people so I am really hoping a step by step guide is possible.
Thanks

.....  Word?!?! .....

youtube has a ton of non-hardcore arduino vids, including lib vids

Usually, the documentation is the correct place to start.

A lot of the Adafruit tutorials are targetted at absolute beginners.

Start with the newest Arduino IDE. At this moment that is version 1.8.1.
Try to find the Library Manager. Via the menu: Sketch / Library...
In the Library Manager there is a input field in the upper-right corner where you can search for libraries.
If you can not find the library, then the next step is to download a zip file from Github. There is probably a green button "Clone or Download" on the right side with that project on Github. Use it to download that library and store it. Do not unzip it. In the Arduino IDE in the menu via: Sketch / Library... there is a option to install a .ZIP file. Use that to install the library from Github.
Your projects are probably at: Documents / Arduino
There is also a folder: Documents / Arduino / libraries
That is where the installed libraries will end up. That means you can also add libraries to that folder. Each library in its own sub-folder.


text:
Is there any chance of fixing it?
I am new to arduino and robotic stuffs and I thought it would be a good idea to test circuits on my breadboard using arduino's R3 5V pin as power supply. The accident happened when I short circuited the things on the breadboard and after a while arduino gave off a nasty smell. The only part overheated on arduino was the left side of the micro-controller. After that I cant upload nor run code on arduino.
After I explained you my situation, can you imagine a potential problem?(e.g I mean is it a voltage regultor problem, a micro-controller faillure, both of them, or something else?)
Can I fix it?
(#1 - I know arduino boards are cheap. I just want to know if I can do anything        with that.
#2 - No comments about  the accident accepted.)
Thank's in advance.
Regarding the image, my vendor claims the arduino to be an exact copy of "open-source" arduino R3

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

Can I fix it?

If your power supply still works, there's a decent chance you can repair the board by replacing its microcontroller which is conveniently socketed.

Can I fix it?

it depends on your skills and the nature of the problem and how far you are willing to go to fix it.
I would first try to rule out a supply problem - very rarely a mcu will burn to the extent of giving off smells / overheat. So unplug the mcu and use a multimeter to measure its Vcc vs. GND pin voltage, test trace continuity, etc.
after that, plug in a new / known good chip and see if you could upload code to it.