Hello,
I am working on an optical proximity sensor. For this I use a LED with 0.5ms pulse length at 10Hz. A photo sensor receives the pulses and triggers an interrupt on the arduino. The stronger the reflection , the longer the incoming pulse is.
To get the LED pulses down to 0.5ms I need a fast timer, so I use Timer 1 by using the TimerOne library. To get a high measurement resolution I set the timer period to 8000 ?s. This if too fast to get a 10Hz measurement frequency so I use Timer 2 (MsTimer2 library) To start Timer1 10 times per second.
So far this works fine, but this is my problem: When I take measurements of the incoming pulses, I read TCNT1 as this should hold the counter position for Timer 1. But depending on the position and pulsewidth of the incoming pulse, sometimes the TCNT1 value is greater at the first interrupt (falling) than on the second interrupt (rising).
I understand this is because the Timer1 lib uses phase-correct PWM, so the timer counts up and down. To change this, I am attempting to set the timer to fast PWM, by using some code I found on the internet:
pinMode(10, OUTPUT);
TCCR1A = _BV(COM2A0) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR1B = _BV(WGM22) | _BV(CS22);
TCCR1B = TCCR1B & 0b11111000 | 0x03;
//Set duty cycle
OCR1B = 62; // 500 ?s
This code works, but the first problem I run into is starting and stopping this timer. Since now I can't just call Timer1.Stop() as I'm not using this library anymore, how can I stop this timer after each period, so I can start it again using Timer 2?
Also, from what I understand setting the timer divider to 0x03 and duty cycle (OCR1B) to 62 would give me a maximum resolution of 62. Or am I wrong? I was getting around 6000 with the standard timer method but I'm not sure what settings would work best.
If anyone can help out, I would really appreciate that!
Thanks!