View: 152|Reply: 1

Banana Pi Lesson 04 Fix

[Copy link]

2

Threads

3

Posts

22

Credits

Newbie

Rank: 1

Credits
22
Post time 2024-8-18 03:46:04 | Show all posts |Read mode
Edited by 1723660543 at 2024-8-20 03:42 AM

OK, I have been fighting this for a few days.  Finally, I realized that it was not me.  The code for the Banana Pi is half-baked!  I tried re-flashing, but their instructions were wrong.  Was able to reflash with CircuitPython website.  Then, lesson 04 Ultrasonic would hang.  Now, I knew, the code was unreliable.  Turned out the code was wrong!  The Raspberry Pi code was totally different, and made perfect sense.  So, I transferred the concepts into the Banana Pi code:
import time
import board
import pwmio
import time
import digitalio

class Ultrasonic():
    # Define output(trig) and input(echo) pins.
    def __init__(self):
        #Define output(trig) and input(echo) Pin.
        self._trig           = digitalio.DigitalInOut(board.GP3)
        self._trig.direction = digitalio.Direction.OUTPUT
        self._trig.value     = 0
        self._echo           = digitalio.DigitalInOut(board.GP2)
        self._echo.direction = digitalio.Direction.INPUT

    def get_distance(self):
        self._trig.value = 1
        time.sleep(0.000002)
        self._trig.value = 0
        # Wait for the echo pin to become high
        while (self._echo.value) == False:
            pass
        # Record start time            
        start = time.monotonic_ns()
        # Wait for the echo pin to lower
        while self._echo.value == True:
            pass
        # End of record time
        end = time.monotonic_ns()
        # Calculate the duration of the pulse (nanosecond)
        duration = end - start
        # Distance (cm) calculated based on the speed of sound (343 m/s)
        distance = ((duration / 2)/1000) * 0.0343
        # Return distance value
        return distance

if __name__ == '__main__':
    ultrasonic = Ultrasonic()
    while True:
        value = ultrasonic.get_distance()
        print("Distance: {:.2f}cm" .format(value))
        time.sleep(1)



Reply

Use magic Report

2

Threads

3

Posts

22

Credits

Newbie

Rank: 1

Credits
22
 Author| Post time 2024-8-18 09:33:36 | Show all posts

Nevermind

Edited by 1723660543 at 2024-8-20 03:44 AM

Nevermind
Reply

Use magic Report

You have to log in before you can reply Login | Sign Up

Points Rules