I want to measure pulse duration, but I need to measure 4 signals so I can't use Timer capture interruption as there is only 1 pin ICP1 providing that option (or can?). So I try to implement something like arduino pulseIn with the difference that I use timer (arduino has some other implementation but very similar).
The actual problem is that pulseIn doesn't return any and just goes on working in the endless loop.
Using ATmega16. Testing only on PB2 now.
unsigned long pulseIn()
{
unsigned long duration = 0;
DDRB = 0x00;
/* Initiate timer and wait for the end of previous pulse*/
initTime1();
while(getPortBPin(2) == 1);
/* Wait for current pulse begin */
while(getPortBPin(2) != 1);
/* Time before previous pulse ended */
TCNT1 = 0;
overflowCounter = 0;
/* Wait for current pulse end */
while(getPortBPin(2) == 1);
/* Closk freq is 2 MHz = 1/2 us per tick */
duration = (TCNT1+overflowCounter*65536)/2;
overflowCounter = 0;
stopTimer1();
return duration;
}
void initTime1()
{
/* Noise filtering */
TCCR1B = (1 << ICNC1);
/* Set prescaling factor to 8 */
TCCR1B |= (1 << CS11);
/* Enable overflow interruption */
TIMSK = (1 << TOIE1);
/* Clear counter */
TCNT1 = 0;
}
void stopTimer1()
{
TCCR1B = 0;
TIMSK = 0;
TCNT1 = 0;
}
uint8_t getPortBPin(uint8_t pin)
{
if(pin < 0 || pin > 8)
{
return 0;
}
return (uint8_t)((PINB >> pin) & 0x01);
}
UPDATE
That's my proteus scheme. Signal comes from generator. Frequency is 1kHz and width is 50%. Аmplitude is 5 volts.
UPDATE
Sorry, that was a stupid mistake. It works fine. Debug things I have didn't work as expected.