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

[![Valid XHTML][1]][1]
<sub>(source: [cloudfront.net](https://d2r5da613aq50s.cloudfront.net/wp-content/uploads/381382.image2.jpg))</sub>

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:

1) 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?

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

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

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

5) 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

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

title: Newbie Arduino DC motor problem

Answers: 2

body:
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.

1. 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.**

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

3. 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.

4. 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.

5. 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.

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

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

8. 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).

9. 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][1]. Also something about [open collector configurations][2] may help.

10. 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.

  [1]: http://www.evilmadscientist.com/2013/base-resistor/
  [2]: http://www.evilmadscientist.com/2012/basics-open-collector-outputs/

body:
***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!


body:
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...

title: Why am i getting "phantom" readings from a flowmeter?

Answers: 0


body:
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!

title: Reading PushButton status with pyserial

Answers: 1

body:
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':


body:
I've followed the directions from [this answer][1], 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][2].

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.

  [1]: https://arduino.stackexchange.com/a/26069/30872
  [2]: https://www.arduino.cc/en/Tutorial/ToneMelody?action=sourceblock&num=2

title: Is this example for playing music without delay correct?

Answers: 2

body:
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.

body:
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.


body:
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?

title: Need clarification with arduino syntax

Answers: 2

body:
It's coming from the program itself:

    int direction = 1;

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

body:
You defined the `direction` variable on the top with:

    int direction = 1;


body:
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.

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

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

title: Why does my LCD screen display white rectangles?

Answers: 1

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


body:
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?

title: Using analog in to read a push button

Answers: 4

body:
> 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.

body:
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.
[![ladder circuit with 5 switches and 9 resistors][1]][1]

  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;`.

  [1]: https://i.stack.imgur.com/EdrIZ.png

body:
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
    }

body:
> 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][1] 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);
      }
    }

  [1]: https://learn.sparkfun.com/tutorials/pull-up-resistors/all


body:
I'm using [Arduino Makefile][1] to compile sketches for Uno and Mega boards. I'm now trying to compile a sketch for an [Arduino Uno Pro][2], 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.

  [1]: https://github.com/sudar/Arduino-Makefile
  [2]: http://www.hobbytronics.co.uk/arduino-uno-pro

title: How to program an Arduino Uno Pro with a makefile?

Answers: 1

body:
After you edit your `boards.txt` file to incorporate the Arduino Uno Pro section from near the end of that [Arduino Uno Pro webpage](http://www.hobbytronics.co.uk/arduino-uno-pro) 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`.


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

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

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

  [1]: https://forum.arduino.cc/index.php?topic=266361.0
  [2]: https://i.stack.imgur.com/rQDOY.jpg

title: Arduino Due connection with FLIR Lepton

Answers: 1

body:
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
)

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

  [1]: https://i.stack.imgur.com/LH8nf.png


body:
I have been working on a small project recently. I have a circuit like in the image below:

> Hardware Setup Demultiplexer IR Test

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

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

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

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.

  [1]: https://i.stack.imgur.com/hKtVI.png
  [2]: https://i.stack.imgur.com/O9cYx.png

title: Demultiplexing Arduino with C++ code

Answers: 1

body:
The most important document you have to read is called a datasheet. [Here][1] 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...

  [1]: http://www.onsemi.com/pub_link/Collateral/MC14051B-D.PDF


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

Here, it's my code.

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

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

    float MAP;

    float MAP_MIN = 0.85;
    float MAP_MAX = 1.90;

    float LOAD_MIN_MAP_MIN = 2.00;
    float LOAD_MAX_MAP_MIN = 15.00;

    float LOAD_MIN_MAP_MAX = 10.00;
    float LOAD_MAX_MAP_MAX = 85.00;

    float mMAPmin;
    float mMAPmax;

    float yMAPmin;
    float yMAPmax;

    float mMAP;

    float yMAP;

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

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

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

    float TPS;

    float TPS_MIN = 0.00;
    float TPS_MAX = 5.00;

    float LOAD_MIN_TPS_MIN = 2.00;
    float LOAD_MAX_TPS_MIN = 10.00;

    float LOAD_MIN_TPS_MAX = 15.00;
    float LOAD_MAX_TPS_MAX = 85.00;

    float mTPSmin;
    float mTPSmax;

    float yTPSmin;
    float yTPSmax;

    float mTPS;

    float yTPS;

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

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

    int LOAD_MIN = 2;
    int LOAD_MAX = 100;

    float injTime_MIN_LOAD_MIN = 4.00;
    float injTime_MAX_LOAD_MIN = 4.60;

    float injTime_MIN_LOAD_MAX = 8.06;
    float injTime_MAX_LOAD_MAX = 14.86;

    float LOAD;

    float mLOADmin;
    float mLOADmax;

    float yLOADmin;
    float yLOADmax;

    float mLOAD;

    float yLOAD;

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

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

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

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

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

    int RPM_MIN = 400;
    int RPM_MAX = 6000;

    float injTime_MIN_RPM_MIN = 4.00;
    float injTime_MAX_RPM_MIN = 8.06;

    float injTime_MIN_RPM_MAX = 4.60;
    float injTime_MAX_RPM_MAX = 14.86;

    float mRPMmin;
    float mRPMmax;

    float yRPMmin;
    float yRPMmax;

    float mRPM;

    float yRPM;

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

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

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

    float minPosVolGas = 0.00;
    float maxPosVolGas = 2.50;

    float minInjPerPos = 0.35;
    float maxInjPerPos = 0.00;

    float minNagVolGas = 2.50;
    float maxNagVolGas = 5.00;

    float minInjPerNag = 0.00;
    float maxInjPerNag = 0.25;

    float mGasPos, mGasNag;
    float yGasPos, yGasNag;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    }

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

    void countRPM()
    {
      RPMpulses++;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    int RPM_MIN = 400;
    int RPM_MAX = 6000;

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

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

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

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

    float minInjPerPos = 0.35;
    float maxInjPerPos = 0.00;

    float minNagVolGas = 2.50;
    float maxNagVolGas = 5.00;

    float minInjPerNag = 0.00;
    float maxInjPerNag = 0.25;

    float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

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

    const int kPinInj = 13;

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

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

      pinMode(kPinInj, OUTPUT);
    }

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

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

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

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

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

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

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

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

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

      LOAD = (yFinalTPS + yFinalMAP) / 2;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    void countRPM()
    {
      RPMpulses++;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    int RPM_MIN = 400;
    int RPM_MAX = 6000;

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

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

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

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

    float minInjPerPos = 0.35;
    float maxInjPerPos = 0.00;

    float minNagVolGas = 2.50;
    float maxNagVolGas = 5.00;

    float minInjPerNag = 0.00;
    float maxInjPerNag = 0.25;

    float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

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

    const int kPinInj = 13;

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

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

      pinMode(kPinInj, OUTPUT);
    }

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

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

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

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

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

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

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

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

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

      LOAD = (yFinalTPS + yFinalMAP) / 2;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    void countRPM()
    {
      RPMpulses++;

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

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

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

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

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

Answers: 1

body:
Here is how I would do it:

    volatile uint32_t injTime = 0;

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

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

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

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

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

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

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

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

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


body:
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();
    }

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

Answers: 1

body:
Here, Updated Code...

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

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

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

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

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

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

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

    }

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

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

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

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


body:
I have the 14051 Demux set up with an Arduino Uno R3 and I am able to light up all three LED's at once with a 1 second delay however, I want to light up 1 LED at a time how can I do this?

> My Hardware Setup

[![My Hardware Setup][1]][1]

> Sketch

    /*  Arduino sketch   */

    int64_t wait= 1000;
    void setup()
    {
      pinMode(7,OUTPUT);
      digitalWrite(7,LOW);
      DDRB = 0b00000111;  //PORT 8,9,10 as output
      PORTB = 0b00000000; //PORT 8,9,10 set to LOW
    }

    void loop()
    {
      PORTB=0b00000000; //Data falow - X0
      uint8_t Sensor0 =  analogRead(A0); //read data from X0
      delay(wait);

      PORTB=0b00000001;  //Data flow - X1
      uint8_t Sensor1 =  analogRead(A0); //read data from X1
      delay(wait);

      PORTB=0b00000010;  //Data flow - X2
      uint8_t Sensor2 =  analogRead(A0); //read data from X2
      delay(wait);

      digitalWrite(7,HIGH);  // Inhibit / stop all data
      delay(wait);
      digitalWrite(7,LOW);  // Inhibit /  let data flow
    }

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

title: Demux 1 LED at a time

Answers: 0


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

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

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

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

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

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

Answers: 1

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

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

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

    const uint8_t pin = ...;
    uint8_t frequency;

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

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

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


body:
I am trying to get the MAC address that is stored on the Wiznet w5500 chip.

On [page 29 - click here][1], it has the address of the values. It state that "This block can be selected by the BSB[4:0] value of SPI Frame". Then it lists the addresses of the MAC block from 0x001E to 0x0023.

How do I read these blocks using the SPI library? What does the BSB[4:0] mean?

EDIT 1: I am looking through the Wiznet Arduino library and it looks like there is a way to access the mac address through

  [1]: http://wizwiki.net/wiki/lib/exe/fetch.php?media=products:w5500:w5500_ds_v107e_160224.pdf

title: Reading values from Wiznet w5500 chip over SPI

Answers: 0


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

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

the code is :

    {

    #include <Wire.h>

    #define EEPROM_ADDR 0xA0;

    void setup()
    {

      Wire.begin();

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

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

      at=((t*192));

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

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

        deviceaddress = deviceaddress >> 1;

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

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

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

title: 24LC1025 Arduino - Data Writing Problem

Answers: 1

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

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

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


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

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

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

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

The output is:

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

Any idea what am I doing wrong when writing?

title: Simple reading and writing on Floppy Disk

Answers: 1

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

I think that need to be

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

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


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

My void loop function in Arduino Uno is

    void loop() {

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

    while(1){

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

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

            }
                                   }

  }

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

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

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

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

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

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

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

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

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

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

My problem, is that the program stops in the line

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

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

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

Any suggestion?

title: Stop time in Tkinter Stopwatch with a PushButton

Answers: 1

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

            baseIndex += CHUNKSIZE;

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

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

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

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

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

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

Any help would be greatly appreciated!

Thanks!

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

Answers: 1

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

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

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

---

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

One of your major problems is this:

    const char * const scriptTable[] PROGMEM =

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

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

    uint_farptr_t  scriptTable [TABLE_SIZE] =

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

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

    #include "code.cpp"

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

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

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

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

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

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

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

    void loop()
    {
    }

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

As in:

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

    #include <Arduino.h>

    const char script1[] PROGMEM =  {

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

    const char script2[] PROGMEM =  {

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

    const char script3[] PROGMEM =  {

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

Output:

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

    ...

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

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


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

title: Aurduino Smart Wifi Wall Socket

Answers: 2

body:
All the Hardware mentioned are correct,

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

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

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

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

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

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

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

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


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

title: Store a variable?

Answers: 6

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

    #include <EEPROM.h>

    int valAddr = 0;

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

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

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

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

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

    #define analogPin 0
    #define buttPin 3

    int analogVal = 0;

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

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

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

        // You can do stuff here
    }

body:
My recommendation:

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

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

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

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

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

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

    void loop() {

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

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

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

    void loop(){
       int value, freeze;

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

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

body:
> it will continuously read my analog input.

easy:

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

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

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


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

I'm trying to start with the sample code

    /*
      SD card read/write

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

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

     This example code is in the public domain.

     */

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

    File myFile;

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

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

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

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

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

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

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

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

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

title: Read value from a file inside SD card

Answers: 2

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

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

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

    /*
     SD card read/write

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

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

    This example code is in the public domain.

    */

    #include <SD.h>

    File myFile;
    char buf[10];

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

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

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

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

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

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


body:
As I couldn't make my ESP8266 be programmed using an Arduino board as FTDI bridge, I decided to buy an FTDI232 board to upload code directly to ESP module via USB. However, when new I connected it to my PC and nothing happened, no new device's notification, not listed on Device Manager; then I downloaded the chip and VCP drivers, installed them, and it keeps not communicating and not even showing its port as busy at Arduino IDE. Actually, I just disabled driver signature enforcement, repeated the process but communication between FTDI and PC keeps dead.

By testing uploading code to an Arduino Micro via FTDI (no USB connected to Micro), I checked Tx/Rx signals with an oscilloscope and both were not responding.

May it be a problem of communication PC<--->FTDI board? Or could it be that FTDI's chip is fried?

Thanks.

title: How to verify that my FTDI bridge for ESP8266 is communicating with my PC?

Answers: 0


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

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

    AT+CCLK?

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

    OK

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

My code currently:

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

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

    void loop() {

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

    SendTextMessage();

    }

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

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

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

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

Answers: 1

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

I am a computer engineer and very new to Arduino.

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

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

Answers: 3

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

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

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

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

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

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

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

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

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

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

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

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

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

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

**EDIT:** additional information

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

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

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

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

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

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

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

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

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


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

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

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

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

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

    }
      if(ps2x.ButtonReleased(PSB_RED))

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

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

Answers: 1

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


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

    /*
     SD card read/write

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

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

    This example code is in the public domain.

    */

    #include <SD.h>

    File myFile;
    char buf[10];

    char bufStringa[24];

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

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

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

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

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

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

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

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

title: How to find integer inside a file with STRNCMP

Answers: 1

body:
Maybe make it as:

    char id[] = "18";

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

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

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

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