I am trying to read my ultrasonic sensor. It sends a pulse in the trigger pin and the echo pin receives the pulse. Using pulseIn I can know exactly the time it took to the pulse go and back. But I need to use port register which is much faster and I need it to be fast in this specific case.
My code is very simple:
void setup() {
Serial.begin(9600);
//pin 12 as output
DDRB = B00010000;
//pin 12 as low
PORTB = B00000000;
}
void loop() {
//pin 12 as high
PORTB = B00010000;
delayMicroseconds(10);
//pin 12 as low
PORTB = B00000000;
long start_time = micros();
//While reading high in pin 13 keep running the loop
while (PINB & B00100000)) {
}
Serial.println(micros() - start_time);
delay(1000);
}
The problem is that it does not work, I mean, the while loop is not being processed so the serial is always printing a very small number. It doesnt matter if I move the ultrasonic sensor to distant walls the while loop still does not work. What am I doing wrong?