I am using C/C++ on a rapsberry pi Pico and this is the code I wrote for the sensor:
#include <FreeRTOS.h>
#include <task.h>
#include <stdio.h>
#include <queue.h>
#include <memory>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "one_wire.h"
#include "LCD_I2C.hpp"
#include "i2c-display-lib.h"
#include "hardware/gpio.h"
#include "hardware/timer.h"
void setupUltrasonicPins(uint trigPin, uint echoPin)
{
gpio_init(trigPin);
gpio_init(echoPin);
gpio_set_dir(trigPin, GPIO_OUT);
gpio_set_dir(echoPin, GPIO_IN);
gpio_pull_up(echoPin);
}
int getPulse(uint trigPin, uint echoPin)
{
int loop1 = 0;
int loop2 = 0;
sleep_us(2);
gpio_put(trigPin, 1);
sleep_us(20);
gpio_put(trigPin, 0);
sleep_us(2);
while (gpio_get(echoPin) == 0)
{
loop1++;
sleep_us(1);
if(loop1 > 5000){
printf("\n I got here 1");
break;
}
}
while (gpio_get(echoPin) != 0 )
{
loop2++;
sleep_us(1);
if(loop2 > 3000){
printf("I got here 2");
return 0;
}
}
return loop2;
}
float getCm(uint trigPin, uint echoPin)
{
int pulseLength = getPulse(trigPin, echoPin);
return (float)pulseLength/2 * 0.0343;
}
int main() {
stdio_init_all();
//sleep_ms(10000);
uint trigPin = 17;
uint echoPin = 16;
setupUltrasonicPins(trigPin, echoPin);
while(1){
printf("\n %.2f cm",getCm(trigPin, echoPin));
sleep_ms(100);
}
}
Please ignore the extra libraries.
With this sensor you basically have to check how much time has passed between the trigger being activated and the echo receiving a signal so that you can calculate the distance.
The code somewhat works BUT it will show a value for the distance that is always about 30% smaller than the actual distance and from time to time it will fail to provide a value and in the first while
it will just timeout and print the message "I got here 1". Sometimes it will also just print a small value like 0.02 for no reason.
Here is the sample of what the result looks like:
31.59 cm
31.73 cm
31.59 cm
0.02 cm
31.59 cm
31.59 cm
31.73 cm
32.02 cm
31.59 cm
31.61 cm
31.86 cm
31.61 cm
31.73 cm
31.66 cm
31.86 cm
31.88 cm
31.88 cm
31.88 cm
32.00 cm
I got here 1
0.00 cm
I got here 1
0.00 cm
31.88 cm
31.61 cm
31.61 cm
31.88 cm
31.92 cm
I got here 1
0.00 cm
31.88 cm
31.88 cm
32.00 cm
0.02 cm
0.02 cm
31.59 cm
31.59 cm
31.88 cm
32.16 cm
0.02 cm
0.00 cm
32.43 cm
32.16 cm
32.43 cm
I got here 1
0.00 cm
I got here 1
0.00 cm
This is what my setup looks like. Just ignore the buzzer in the pic and consider that I used other pins for the trigger and echo.
Can somebody please help me understand this?