Sensor ultrasonic Timer1 , using only register code

I need for my project a code for sensor ultrasonic for measure distance using timer1 . I tried everything but the timer1 never stops , and is only increasing , here is the code for timer1
I can't use libraries or function which are already in arduino.

The TRIG pin and Echo pin are on pins 2,3 ;
I have the timer0 to generate a PWM signal so i can't use that timer.
What's wrong with my code?

const int trigPin = 2;
const int echoPin = 3;

volatile unsigned long timer1_overflow_count = 0; // Global variable to keep track of timer overflows

ISR(TIMER1_OVF_vect) {

timer1_overflow_count++;
Serial.println(timer1_overflow_count);
SREG &= ~(1<<SREG_I);

}

float measureDistance() {

PORTD |= (1 << trigPin);
delayMicroseconds(10);
PORTD &= ~(1 << trigPin);

unsigned long duration =microsL();
delay(100);
float distance = duration * 0.0343 / 2.0;
Serial.println(duration);
return distance;
}

unsigned long clockCyclesPerMicrosecond2() {
return F_CPU / 16000000UL;
}

void timer1_init() {
// Set Timer 1 to normal mode with a prescaler of 64
TCCR1A = 0;
TCCR1B = (1 << CS11) | (1 << CS10); // prescaler 64

// Enable Timer/Counter1 overflow interrupt
TIMSK1 |= (1 << TOIE1);  

}

uint32_t microsL() {
uint32_t m;

uint8_t oldSREG = SREG;
SREG &= ~(1<<SREG_I);


m = timer1_overflow_count;

uint16_t t = TCNT1;
if ((TIFR1 & (1 << TOV1)) && (t < 65535))
    m++;


SREG = oldSREG;

return ((m << 16) + t) * (64 / clockCyclesPerMicrosecond2());

}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.