How to replace the pin 2 in arduino uno

Hello,
Im using two sensor and all of them using interrupt
the first use juste pin 2 (imu6050) and the second (rotating encoder) use pin 2 and 3.
I don't have an other arduino board, so I've to keep my arduino uno and use both of sensors in the same time.

This is my code

#include <MPU9250.h>

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "Wire.h"
// ---------------------------------------------------------------------------
#define YAW      0
#define PITCH    1
#define ROLL     2

MPU6050 mpu;
// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
int a=0;
double t1;
volatile long temp, counter = 0; //This variable will increase or decrease depending on the rotation of encoder
int Compteur = 0; 
 float b,x=0,m=0;
// Définition des broches d'entrées
float dist=0,mm,dmm=0,pmm=0,amm=0;  
Quaternion q;        // [w, x, y, z]         quaternion container
VectorFloat gravity; // [x, y, z]            gravity vector
float ypr[3];        // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

volatile bool mpuInterrupt = false;     // Indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}
void setup() {
    Wire.begin();
    TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    Serial.begin(9600);//57600    
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();
    mpu.setXAccelOffset(436);//556
    mpu.setYAccelOffset(-1485);//1448
    mpu.setZAccelOffset(914);//902
    mpu.setXGyroOffset(47);//81
    mpu.setYGyroOffset(-24);//-13
    mpu.setZGyroOffset(-28);//-27/8
    if (devStatus == 0) {
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0 : #pin2)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }
     pinMode(2, INPUT_PULLUP); // internal pullup input pin 2 
  
  pinMode(3, INPUT_PULLUP); // internalเป็น pullup input pin 3
   //Setting up interrupt
  //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
  attachInterrupt(0, ai0, RISING);
   
  //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
  attachInterrupt(1, ai1, RISING);
}
void loop() {
    if( counter != temp ){
 dist=counter*1.95;
  Serial.println (dist);
  temp = counter;
  }
    // If programming failed, don't try to do anything
    if (!dmpReady) {
        return;
    }
    while (!mpuInterrupt && fifoCount < packetSize) {
    }
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();
    fifoCount = mpu.getFIFOCount();
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));
    } else if (mpuIntStatus & 0x02) {
        while (fifoCount < packetSize) {
            fifoCount = mpu.getFIFOCount();
        }
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        t1=millis();   
    }
pmm=dist;
dmm=pmm-amm; 
x=x+dmm*cos(-ypr[YAW]);
m=m+dmm*sin(-ypr[YAW]);
amm=pmm;
//Serial.print(dist);
 //Serial.print("\t");
//Serial.print(amm);
// Serial.print("\t");
//Serial.print(dmm);
// Serial.print("\t");
//Serial.print(x);
// Serial.print("\t");
//Serial.print(m);
// Serial.print("\t");
//Serial.println(-ypr[YAW] * (180 / M_PI));
//Serial.print("   ");
//Serial.println(mm,3);
     delay(1);
}
void ai0() {
  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
  // Check pin 3 to determine the direction
  if(digitalRead(3)==LOW) {
  counter++;
  }else{
  counter--;
  }
  }
 void ai1() {
  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
  // Check with pin 2 to determine the direction
  if(digitalRead(2)==LOW) {
  counter--;
  }else{
  counter++;
  }
  }

Read the forum guidelines. Go back and post your code in code tags.
Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

You cannot use the same interrupt pin for 2 different things.

Besides the external interrupts (pins 2 and 3) there are pin change interrupts.

@dib_islam, your topic has been moved to a more suitable location on the forum.

Many pins can be used for Pin Change Interrupts. This is like an External Interrupt except the only mode is "CHANGE" and multiple pins use the same interrupt. When the interrupt happens you have to compare the new pin state against the old pin state to see if the interrupt was caused by a RISING or FALLING edge.

1 Like