タヒチ モーレア島の夕日

エデン

それはまだ見ぬ自律航行型の水上ヴィラ

PythonとFlaskでブラウザからRaspberry Pi上のサーボを動かす

Raspberry Piでサーボが動かせるようになったので、今度はブラウザ経由でサーボを動かしたいですよね。Raspberry Pi上でWEBサーバを動かすには色々と方法があるようですが、Flaskが簡単そうなのでトライしてみようと思います。

まずはpipをインストール

sudo apt-get -y install python3-pip

つぎにFlaskをインストール

pip install flask

そしてテスト用のミニアプリ

#!/usr/bin/env python3
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Web App with Python Flask!'

app.run(host='0.0.0.0', port=5000)

で、実行

./app.py
 * Serving Flask app 'app'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://192.168.1.93:5000
Press CTRL+C to quit

なんかワーニング出たけど・・・。
ブラウザでhttp://192.168.1.93:5000 にアクセスしてみてこんな感じに表示されていればとりあえずは成功かな。

つぎはサーボを動かすために /run/Servo18.target に角度を書き込むアプリを作ります。ファイル構成は以下のような形です。

app.py
templates/
└index.html

#!/usr/bin/env python3
from flask import Flask, render_template, request
T_FILE = '/run/Servo18.target'
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        target = request.form['servo']
        with open(T_FILE, 'w', encoding='utf-8') as f:
            f.write(target)
        return render_template('index.html', target=target)
    else:
        return render_template('index.html')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
<DOCTYPE html>
<html>
    <head>
        <title>controller</title>
        <meta name="viewport" content="width=240">
    </head>
    <body>
    <form method="POST">
    <!-- 変数targetに値があるとき -->
    {% if target %}
        <input type="range" name="servo" min="0" max="180" value="{{ target }}" onchange="submit(this.form)">
    {% else %}
        <input type="range" name="servo" min="0" max="180" value="90" onchange="submit(this.form)">
    {% endif %}
        <!--
        <input type="submit" value="送信">
        -->
    </form>
    </body>
</html>

これでフォームから送信した角度にサーボが動きます。
サーボを動かすプログラムは以下のページで作成しています。


Posted

in

,

by

Tags: