// ReadingSlowerThanChanges
// https://wokwi.com/projects/428996163300913153
// for https://forum.arduino.cc/t/problems-with-photodiode-ir-receiver/1372146/303?u=davex
/*
This sketch puts a low-duty cycle pulse out
on pin 9 using hardware timer 1, and measures the toggling with pin A1
Note the occasional missed pulses and unusually long durations generated
by the while(digitalRead()); interacting with the perfectly regular hardware
timeer pulse train.
Try fiddling with the duty cycle.
*/
#include <TimerOne.h>
const int fanPin = 9;
const int period = 1000000 / 38000; // ~38kHz
const float Duty = 10; // 0.05 to 95.5;
#define IR_PIN A1
unsigned long durations[300];
unsigned long prevMicros;
unsigned long newMicros;
int count = 0;
bool endit = false;
void setup(void)
{
Serial.begin(115200);
Timer1.initialize(period); //
Timer1.pwm(fanPin, (Duty / 100) * 1023);
Serial.print("PWM Period = ");
Serial.print(period);
Serial.print(" Hz = ");
Serial.print(1000000.0/period);
Serial.print("\nDuty Cycle = ");
Serial.print(Duty);
Serial.print(" Pulse Width = ");
Serial.println(Duty * period / 100);
}
void loop() {
count = 0;
endit = false;
while (digitalRead(IR_PIN) == HIGH); // Wait for signal to go LOW
prevMicros = micros();
while ((count < 300) && (endit == false)) {
newMicros = micros();
durations[count++] = newMicros - prevMicros;
prevMicros = newMicros;
while (digitalRead(IR_PIN) == LOW);
newMicros = micros();
durations[count++] = newMicros - prevMicros;
prevMicros = newMicros;
while (digitalRead(IR_PIN) == HIGH) {
if ((micros() - prevMicros) > 2000000) {
endit = true;
break;
}
}
}
Serial.println("Signal:");
for (int i = 1; i < count; i++) {
Serial.print(durations[i]);
Serial.print(" ");
}
Serial.println("\n---");
delay(5000); // Pause between readings
}