Problem to read pwm

Hi,

I have used Arduino Mega to generate a pwm signal. It looks perfect (see the first picture) on the oscilloscope.

Now I am trying to read that pwm wave with the same Arduino board using the Interrupts and digital read functions.

The problem is that when I put a wire from pin 12 (where pwm is coming out) and pin 3 (where digitalread in connect) the pwm signal change (see the second picture). I have already putted a 10K resistor between pin 3 and GND but nothing is changed.

Here is a part of the code that I am using:

attachInterrupt(digitalPinToInterrupt(inPwm) , mydigitalread , CHANGE); 

void mydigitalread() {
  long int val1;
  val = digitalRead(inPwm);
  Serial.print(val);
  Serial.print("  ");
  Serial.println(micros());
  
  if (val == 0){
    val1 = 2;  //b00000010
  }
  if (val == 1){
    val1 = 1; //b00000001
  }
  digitalPotWrite(0);
  digitalPotWrite(val1);
}

Any idea why the signal change and how to resolve it

Thanks,

The intr.routine is very slow (serial.print) and it disables interrups.
I'd try remove this changes routine.. and take another look at the scope.

void mydigitalread() {
  byte val = digitalRead(inPwm);
  //  Serial.print(val);
  // Serial.print("  ");
  // Serial.println(micros());
   if (val == 0) val1 = 2;  else val1 = 1; // something is not OK here
  //digitalPotWrite(0);
  digitalPotWrite(val1); // this is an error.. Digitalwrite is 0 or 1
}

You could also use one Arduino to generate the PWM signal and another to read it. If you just want to try reading the duration of a square wave then use your scope probe calibrator signal as the source. There is also a function for reading pulse width, pulseIn().

Hi,

thank you for your help.

I have tried to disable serial.print but the problem was still there.

I solved using two Arduino boards: one to generate the PWM and the other to read the signal and perform some functions during the rising and falling of the signal.

If you willing to average the PWM value a bit and have an interrupt pin available to use then the example sketch attached will give you the PWM frequency and duty cycle.

Frequency_Counter.ino (2.73 KB)