プラントモニター

このプロジェクトでは、光の強度と土壌の水分レベルの両方を検出し、I2C LCD1602に表示します。土壌の水分が不足していると感じたら、ボタンモジュールを押して鉢植えに水をやることができます。

_images/plant_monitor.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に保存し、例えば plant_monitor.ty という名前を付けます。

    from robot_hat import ADC, Motors, Pin
    import LCD1602
    import time
    import threading
    
    from robot_hat.utils import reset_mcu
    
    reset_mcu()
    time.sleep(.1)
    
    
    # Initialize objects
    light_sensor = ADC(1)
    moisture_sensor = ADC(0)
    motors = Motors()
    button = Pin('D0')
    
    # Thread running flag
    running = True
    
    def init_lcd():
        LCD1602.init(0x27, 1)
        time.sleep(2)
    
    def update_lcd(light_value, moisture_value):
        LCD1602.write(0, 0, 'Light: %d  ' % light_value)
        LCD1602.write(0, 1, 'Moisture: %d  ' % moisture_value)
    
    def read_sensors():
        light_value = light_sensor.read()
        time.sleep(0.2)
        moisture_value = moisture_sensor.read()
        time.sleep(0.2)
        return light_value, moisture_value
    
    def control_motor():
        global running
        while running:
            button_pressed = button.value() == 0
            if button_pressed:
                motors[1].speed(80)
                time.sleep(0.1)
            else:
                motors[1].speed(0)
                time.sleep(0.1)
            time.sleep(0.1)
    
    def setup():
        init_lcd()
    
    def destroy():
        global running
        running = False
        LCD1602.clear()
    
    def loop():
        global running
        while running:
            light_value, moisture_value = read_sensors()
            update_lcd(light_value, moisture_value)
            time.sleep(.2)
    
    if __name__ == '__main__':
        try:
            setup()
            motor_thread = threading.Thread(target=control_motor)
            motor_thread.start()
            loop()
        except KeyboardInterrupt:
            motor_thread.join()  # Wait for motor_thread to finish
            print("Program stopped")
        except Exception as e:
            print("Error:", e)
        finally:
            motors[1].speed(0)
            time.sleep(.1)
            destroy()
            print('end')
    
  4. このコードを実行するには、 sudo python3 plant_monitor.ty コマンドを使用します。