RaspberryPi/RaspberryPi_Linux

RbPi_04.web을 이용해서 LED 제어하기

웹 만들기

from flask import Flask

app = Flask(__name__) #__name__ 이름을 이용한 Flask객체를 생성

@app.route('/')         #클라이언트가uri로/를요청하면
def Hello():            #뷰함수가 실행된다.
        return "Hello Flask!!"  #반드시 return이 있어야 한다.

if __name__ == "__main__":      #직접 실행을 위한 조건
        app.run(host = "0.0.0.0", port="8080")

 

HTML 파일 생성

<!DOCTYPE html>
<html>
<head>
        <meta charset = "UTF-8">
        <title> HOME IOT NEWWORK </title>
</head>
<body>
        <h1> LED ON OFF </h1>
        <form action = '/data' method = 'post'>
            <input type = "submit" name = "led" value = "on" onclick = "alert('Led ON~!!')" >

                <input type = "submit" name = "led" value = "off" onclick = "alert('Led OFF~!')">

                <input type = "submit" name = "led" value = "clean" onclick = "alert('Clean UP~!')">

        </form>

</body>
<footer>
        <h1>Hi<h1>
</footer>

</html>

 

웹으로 불켜기!

from flask import Flask, request, render_template
import RPi.GPIO as GPIO

app = Flask(__name__)

ledPin = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(ledPin, GPIO.OUT)

@app.route('/')
def home():
        return render_template("index.html")

@app.route('/data', methods = ['POST'])
def data():
        data = request.form['led']
        if data == 'on':
                GPIO.output(ledPin, True)
        elif data == 'off':
                GPIO.output(ledPin, False)
        elif data == 'clean':
                GPIO.cleanup()

        return "LED" + data

if __name__ == '__main__':
        app.run(host = '0.0.0.0', port="8080")