Skip to content

Commit

Permalink
ultrasonic
Browse files Browse the repository at this point in the history
  • Loading branch information
ImplFerris committed Oct 25, 2024
1 parent 1d51e37 commit 44376ba
Show file tree
Hide file tree
Showing 5 changed files with 210 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@
- [PWM](./blinky/pwm.md)
- [Watchdog](./blinky/watchdog.md)
- [Using External LED](./blinky/external-led.md)
- [Ultrasonic](./ultrasonic/index.md)
- [How it works?](./ultrasonic/concepts.md)
- [Light it Up](./ultrasonic/action.md)

- [Resources](./resources.md)
Binary file added src/images/hc-sr04-ultrasonic.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
148 changes: 148 additions & 0 deletions src/ultrasonic/action.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
## Action

We'll start by generating the project using the template, then modify the code to fit the current project’s requirements.


## Generating From template

Refer to the [Template section](../cargo-generate.md) for details and instructions.

To generate the project, run:

```sh
cargo generate --git https://github.com/ImplFerris/pico2-template.git
```
Provide a project name and select `rp-hal` as the HAL.

Then, navigate into the project folder:
```sh
cd PROJECT_NAME
```

## Setup the LED Pin
You should understand this code by now. If not, please complete the Blink LED section first.

Quick recap: Here, we're configuring the PWM for the LED, which allows us to control the brightness by adjusting the duty cycle.

```rust
let pwm = &mut pwm_slices.pwm6; // Access PWM slice 6
pwm.set_ph_correct(); // Set phase-correct mode for smoother transitions
pwm.enable(); // Enable the PWM slice
let led = &mut pwm.channel_b; // Select PWM channel B
led.output_to(pins.gpio13); // Set GPIO 13 as the PWM output pin
```

## Setup the Trigger Pin
The Trigger pin on the ultrasonic sensor is used to start the ultrasonic pulse. It needs to be set as an output so we can control it to send the pulse.

```rust
let mut trigger = pins.gpio17.into_push_pull_output();
```

## Setup the Echo Pin
The Echo pin on the ultrasonic sensor receives the returning signal, which allows us to measure the time it took for the pulse to travel to an object and back. It’s set as an input to detect the returning pulse.

```rust
let mut echo = pins.gpio16.into_pull_down_input();
```

## 🦇 Light it Up

### Step 1: Send the Trigger Pulse
First, we need to send a short pulse to the trigger pin to start the ultrasonic measurement.

```rust
// Ensure the Trigger pin is low before starting
trigger.set_low().ok().unwrap();
timer.delay_us(2);

// Send a 10-microsecond high pulse
trigger.set_high().ok().unwrap();
timer.delay_us(10);
trigger.set_low().ok().unwrap();
```

### Step 2: Measure the Echo Time
Now, measure the time the Echo pin remains high, which represents the round-trip time of the sound wave.

```rust
let mut time_low = 0;
let mut time_high = 0;

// Wait for the Echo pin to go high and note down the time
while echo.is_low().ok().unwrap() {
time_low = timer.get_counter().ticks();
}

// Wait for the Echo pin to go low and note down the time
while echo.is_high().ok().unwrap() {
time_high = timer.get_counter().ticks();
}

// Calculate the time taken for the signal to return
let time_passed = time_high - time_low;

```

### Step 3: Calculate Distance
Using the measured time, calculate the distance to the object. The speed of sound in air is approximately 0.0343 cm/µs.

```rust
let distance = time_passed as f64 * 0.0343 / 2.0;
```

### Step 3: Calculate Distance
Finally, adjust the LED brightness based on the distance. If the distance is below a certain threshold (e.g., 30 cm), increase the brightness proportionally; otherwise, turn off the LED.

```rust
let duty_cycle = if distance < 30.0 {
let step = 30.0 - distance;
(step * 1500.) as u16 + 1000
} else {
0
};

// Set the LED brightness
led.set_duty_cycle(duty_cycle).unwrap();

```

### Complete Logic of the loop
Note: This code snippet highlights the loop section and does not include the entire code.

```rust
loop {
timer.delay_ms(5);

trigger.set_low().ok().unwrap();
timer.delay_us(2);
trigger.set_high().ok().unwrap();
timer.delay_us(10);
trigger.set_low().ok().unwrap();

let mut time_low = 0;
let mut time_high = 0;
while echo.is_low().ok().unwrap() {
time_low = timer.get_counter().ticks();
}
while echo.is_high().ok().unwrap() {
time_high = timer.get_counter().ticks();
}
let time_passed = time_high - time_low;

let distance = time_passed as f64 * 0.0343 / 2.0;

let duty_cycle = if distance < 30.0 {
let step = 30.0 - distance;
(step * 1500.) as u16 + 1000
} else {
0
};
led.set_duty_cycle(duty_cycle).unwrap();
}
```


## Your Challenge
1. Use Embassy framework instead of rp-hal
2. Use the onboard LED instead
34 changes: 34 additions & 0 deletions src/ultrasonic/concepts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# How Does an Ultrasonic Sensor Work?

Ultrasonic sensors work by emitting sound waves at a frequency too high for humans to hear. These sound waves travel through the air and bounce back when they hit an object. The sensor calculates the distance by measuring how long it takes for the sound waves to return.

<img style="display: block; margin: auto;width:500px" alt="pico2" src="../images/ultrasonic.jpg"/>

- **Transmitter:** Sends out ultrasonic sound waves.
- **Receiver:** Detects the sound waves that bounce back from an object.

**Formula to calculate distance**:
```
Distance = (Time x Speed of Sound) / 2
```

The speed of sound is approximately 0.0343 cm/µs (or 343 m/s) at normal air pressure and a temperature of 20°C.

## Example Calculation:

Let’s say the ultrasonic sensor detects that the sound wave took 2000 µs to return after hitting an object.

Step 1: Calculate the total distance traveled by the sound wave:
```
Total distance = Time x Speed of Sound
Total distance = 2000 µs x 0343 cm/µs = 68.6 cm
```

Step 2: Since the sound wave traveled to the object and back, the distance to the object is half of the total distance:
```
Distance to object = 68.6 cm / 2 = 34.3 cm
```

Thus, the object is 34.3 cm away from the sensor.


24 changes: 24 additions & 0 deletions src/ultrasonic/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Ultrasonic

In this section, we'll learn how to interface the HC-SR04 ultrasonic sensor with a Raspberry Pi Pico 2. Ultrasonic sensors measure distances by emitting ultrasonic sound waves and calculating the time taken for them to return after bouncing off an object.

We will build a simple project that gradually increases the LED brightness using PWM, when the ultrasonic sensor detects an object distance of less than 30 cm.

<img style="display: block; margin: auto;width:500px" alt="pico2" src="../images/hc-sr04-ultrasonic.jpg"/>

## 🛠 Hardware Requirements
To complete this project, you will need:

- HC-SR04 Ultrasonic Sensor
- Breadboard
- Jumper wires
- External LED (You can also use the onboard LED, but you'll need to modify the code accordingly)

The HC-SR04 Sensor module has a transmitter and receiver. The module has Trigger and Echo pins which can be connected to the GPIO pins of a pico and other microcontrollers. When the receiver detects the returning sound wave, the Echo pin goes high for a duration equal to the time it takes for the wave to return to the sensor.

## Setup
- **VCC**: Connect to the 5V pin on the Pico to power the HC-SR04.
- **Trig**: Connect to GPIO 17 on the Pico to start the ultrasonic sound pulses.
- **Echo**: Connect to GPIO 16 on the Pico; this pin sends a pulse when it detects the reflected signal, and the pulse length shows how long the signal took to return.
- **GND**: Connect to the ground pin on the Pico.
- **LED**: Connect the anode (long leg) of the LED to GPIO 13, as in the [External LED setup](../blinky/external-led.md).

0 comments on commit 44376ba

Please sign in to comment.