I'm studying arduino. I generated pulse waves using arduino analog PWM output. Mega pin No.4 -> 980Hz output => approximately 1000Hz => 1ms duration/pulse => 1000us
I used 50% duty cycle, so 500us pulse output.
I connected PWM output to digital input No.10 pin.
And here is my code. (for HIGH pulse duration)
int aoPin = 4; // analog output pin
int diPin = 10; // digital input pin
void setup() {
Serial.begin(9600);
pinMode(aoPin, OUTPUT);
pinMode(diPin, INPUT);
}
void loop() {
unsigned long highPulse = 0; // Pulse length
unsigned long startMicros = micros();
analogWrite(aoPin, 128); // half duty cycle of 980Hz (arduino Mega pin No.4)
while (digitalRead(diPin)) // calculation method 1
{
}
highPulse = micros() - startMicros;
Serial.print("highPulse1 = ");
Serial.print(highPulse);
Serial.print(" / ");
highPulse = pulseIn(diPin, HIGH); // calculation method 2
Serial.print("highPulse2 = ");
Serial.println(highPulse);
delay(1000);
}
The result was 180 / 510 repeatedly.
The PulseIn
function calculated accurate 500us, but my calculated duration was too short (180us).
Even PulseIn
function was executed after my calculation function.
Why? Was My function start delayed?
CodePudding user response:
Change where you call micros() the first time, so you know you do it at a rising edge:
unsigned long startMicros = 0;
analogWrite(aoPin, 128); // half duty cycle of 980Hz (arduino Mega pin No.4)
while (digitalRead(diPin)); // wait while input is high
while (!digitalRead(diPin)); // wait while input is low
startMicros = micros(); // Rising edge detected!
while (digitalRead(diPin)); // wait while input is high
// Falling edge detected, get time difference!
highPulse = micros() - startMicros;