How to Use C SDK to Create UF2 file which Interface Ultrasonic Sensor with Raspberry Pi Pico

Posted

in

by

Tags:

Hardware setup

HC-SR04Raspberry Pi Pico
VCCVSYS
GNDGND
TrigGP2
ECHOGP3

I am using raspberry pi model 3 b+ for the code compilation.

  1. Create the folder named “distance” inside the pico folder
  1. Then Create the test.c and CMakeLists.txt files using touch command.
touch test.c CMakeLists.txt
  1. Copy the pico_sdk_import.cmake file from pico/pico-sdk/external
  2. make the build directory using mkdir command
mkdir build
  1. Here is the CMakeLists.txt code
# Set the minimum required version of CMake
cmake_minimum_required(VERSION 3.13)

# Import the Pico SDK CMake configuration file
include(pico_sdk_import.cmake)

# Set the project name and languages
project(test_project C CXX ASM)

# Set the C and C++ language standards
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

# Initialize the Pico SDK
pico_sdk_init()

# Create an executable target called "test" from the source file "test.c"
add_executable(test
    test.c
)

# Enable USB stdio for the "test" target (used for serial communication)
pico_enable_stdio_usb(test 1)

# Disable UART stdio for the "test" target
pico_enable_stdio_uart(test 0)

# Add extra outputs for the "test" target (e.g., UF2 file)
pico_add_extra_outputs(test)

# Link the "test" target with the pico_stdlib library
target_link_libraries(test pico_stdlib)
  1. Here is the c code that you put inside the test.c file
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/timer.h"

#define TRIG_PIN 2
#define ECHO_PIN 3

float measure_distance() {
    gpio_put(TRIG_PIN, 1);
    sleep_us(10);
    gpio_put(TRIG_PIN, 0);

    uint32_t start_ticks = 0;
    uint32_t end_ticks = 0;

    while (gpio_get(ECHO_PIN) == 0) {
        start_ticks = time_us_32();
    }

    while (gpio_get(ECHO_PIN) == 1) {
        end_ticks = time_us_32();
    }

    uint32_t elapsed_time_us = end_ticks - start_ticks;
    float distance_cm = elapsed_time_us * 0.0343 / 2;

    return distance_cm;
}

int main() {
    stdio_init_all();
    sleep_ms(2000);  // Wait for sensor to stabilize

    gpio_init(TRIG_PIN);
    gpio_set_dir(TRIG_PIN, GPIO_OUT);

    gpio_init(ECHO_PIN);
    gpio_set_dir(ECHO_PIN, GPIO_IN);

    while (1) {
        float distance = measure_distance();
        printf("Distance: %.2f cm\n", distance);
        sleep_ms(1000);
    }

    return 0;
}
  1. after this you need to execute this line of code in the terminal
export PICO_SDK_PATH=../../pico
  1. then execute the following code in the given order
cd build
cmake ..
make

If everything worked, you will have your ulf2 file in your build directory

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *