#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
int main() {
/*
Esta função inicializa todas as interfaces de entrada e saída padrão,
como UART , stdout, stderr (saída de erro padrão), stdin (entrada padrão).
Ela permite usar funções de entrada e saída padrão, como printf() e scanf().
*/
stdio_init_all();
gpio_init(16); // echo
gpio_init(17); // trig
gpio_set_dir(17, GPIO_OUT);
gpio_set_dir(16, GPIO_IN);
while(1) {
gpio_put(17, 1);
sleep_us(10);
gpio_put(17, 0);
unsigned long long int pulse_timer = 0;
for(int i = 0; i < 1000000; i++) {
if(gpio_get(16)) {
break;
}
}
absolute_time_t startTime = get_absolute_time();
while(gpio_get(16)) {
pulse_timer++;
sleep_us(1);
if(pulse_timer > 26100) { // Aproximadamente 450 cm, tempo de ida e volta
printf("Distance too far\n");
pulse_timer = 0; // Reseta o timer para o próximo ciclo
break;
}
}
if (pulse_timer > 0) { // Se pulse_timer foi atualizado, calculamos a distância
absolute_time_t endTime = get_absolute_time();
unsigned long long int pulseLength = absolute_time_diff_us(startTime, endTime);
printf("Distance: %.2f cm\n", (pulseLength / 29.0 / 2.0));
}
sleep_ms(60);
}
}