超音波モジュールからの読み取り

このプロジェクトでは、超音波センサーを使用して距離を測定し、その読み取り値をI2C LCD1602に表示します。

_images/ultrasonic.jpg

手順

  1. このプロジェクトではI2C LCD1602を使用しているため、関連するライブラリをダウンロードして機能させる必要があります。

    cd ~/
    wget https://github.com/sunfounder/raphael-kit/blob/master/python/LCD1602.py
    
  2. I2C用に smbus2 をインストールします。

    sudo pip3 install smbus2
    
  3. 以下のコードをRaspberry Piに保存し、例えば ultrasonic.ty という名前を付けます。

    from robot_hat import ADC, Ultrasonic, Pin
    import LCD1602
    import time
    
    # Create ADC object for photoresistor
    a0 = ADC(0)
    
    # Create Ultrasonic object
    us = Ultrasonic(Pin("D2"), Pin("D3")) //Trig to digital pin 2, echo to pin 3
    
    def setup():
        # Initialize LCD1602
        LCD1602.init(0x27, 1)
        # Initial message on LCD
        LCD1602.write(0, 0, 'Measuring...')
        time.sleep(2)
    
    def destroy():
        # Clear the LCD display
        LCD1602.clear()
    
    def loop():
        while True:
            # Read distance from ultrasonic sensor
            distance = us.read()
            # Display the distance on the LCD
            if distance != -1:
                # Display the valid distance on the LCD
                LCD1602.write(0, 0, 'Dist: %.2f cm   ' % distance)
    
            # Update every 0.5 seconds
            time.sleep(0.2)
    
    if __name__ == '__main__':
        setup()
        try:
            loop()
        except KeyboardInterrupt:
            destroy()
        except Exception as e:
            # Clear the LCD and print error message in case of an exception
            destroy()
            print("Error:", e)
    
  4. このコードを実行するには、 sudo python3 ultrasonic.ty コマンドを使用します。