print("Hello, Pi Pico")
from machine import Pin
import utime
trigger = Pin(2, Pin.OUT)
echo = Pin(3 , Pin.IN)
def ultra():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value()== 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0343) / 2
print("The distance from object is ",distance,"cm")
while True:
ultra()
utime.sleep(1)
1. **Initialize Components**:
- Connect your Raspberry Pi Pico to your computer.
- Make sure you have a compatible MicroPython environment installed on your Pi Pico.
2. **Setup the Hardware**:
- Connect the HC-SR04 ultrasonic sensor to your Raspberry Pi Pico according to the provided JSON configuration:
- Connect the GND (ground) pin of the ultrasonic sensor to any ground (GND) pin on the Pi Pico.
- Connect the VCC (power) pin of the ultrasonic sensor to the 3.3V pin on the Pi Pico.
- Connect the TRIG (trigger) pin of the ultrasonic sensor to GPIO Pin 2 (GP2) on the Pi Pico.
- Connect the ECHO (echo) pin of the ultrasonic sensor to GPIO Pin 3 (GP3) on the Pi Pico.
3. **Flash the Code**:
- Copy the provided Python code into a Python file on your computer.
- Save the file with a `.py` extension, for example, `distance_measurement.py`.
- Use a tool like Thonny or any other MicroPython IDE to flash the code onto your Raspberry Pi Pico.
4. **Run the Code**:
- Once the code is flashed onto your Pi Pico, disconnect it from your computer and power it using a suitable power source, such as a USB power adapter or a battery pack.
5. **Observe the Output**:
- After powering on, your Pi Pico will start executing the code.
- It will continuously measure distances using the ultrasonic sensor and print the results to the serial console.
- Connect your Pi Pico to your computer via USB and open a serial monitor in your preferred IDE or terminal program.
- You should see distance measurements being printed out at regular intervals (every second, according to the code).
6. **Test with Objects**:
- Place objects of varying distances in front of the ultrasonic sensor.
- Observe how the printed distance measurements change as the objects move closer to or farther away from the sensor.
7. **Adjustments**:
- If necessary, you can adjust the code or the hardware setup to suit your requirements.
- For example, you might need to change the GPIO pin numbers in the code if you've connected the sensor to different pins on your Pi Pico.
Following these steps will help you understand how the code interacts with the hardware to perform distance measurements using the ultrasonic sensor with your Raspberry Pi Pico.