라즈베리파이 raspberrypi - LED 제어 및 wep 연동

BABY CAT·2023년 1월 5일
0

raspberrypi

목록 보기
1/13

라즈베리 선 연결하고 (전원선 연결하면 자동 실행)

1. 지니 실행

ㄱ. 파일 위치 확인, 파일 오픈

메뉴 > 열기 > 다른위치 > 컴퓨터 > home > pi > webapps

  • 오픈할 파일 3개 :
    controller.py (라우터) , index.html (홈 화면) , led.html (조작하는 화면)

2. 라즈베리파이 LED 연결하기

ㄱ. LED 의 +극과 -극 구분법

짧은 다리인 -극은 GND에 연결한다 (GND는 = Ground 이고 0볼트는
긴 다리인 +극은 아래 controller.py 코드에서

LED = 14
gpio.setmode(gpio.BCM)
gpio.setup(LED, gpio.OUT, initial =gpio.LOW)

이 부분에서 출력핀을 14로 지정하였기 때문에 GPIO BCM 기준 14번 핀에 연결한다
(아래 핀번호 확인법 참고)

ㄴ. 핀 번호 확인법

LED = 14
gpio.setmode(gpio.BCM)
gpio.setup(LED, gpio.OUT, initial =gpio.LOW)

여기서 gpio.setmode(gpio.BCM) 여기서 BCM 이 부분 때문에
LED = 14로 연결하는 것

만약
gpio.BCM 가 아니라 gpio.BOARD 면
14가 아닌

LED = 8로 잡아줘야 한다.

참고

gpio.BOARD 면


이 번호


gpio.BCM 면

이 번호를 사용한다는 말
(LED=14 여기서 14가 어떤 번호인지)

  • 코드에서 가리키는 핀과 실제로 led의 긴다리가 연결되는 핀이 같도록 잘 보고 연결

3. 코드 실행해 보기

ㄱ. 코드 실행 버튼 확인

ㄴ. 코드 실행

controller.py 에서 ㄱ. 코드실행버튼을 누른다

이 화면에서 ctrl 을 누른 상태에서 http://0.0.0.0:5000/
을 마우스로 클릭
(인터넷창 url: http://0.0.0.0:5000/ 로 이동하는 것이니
그냥 url로 0.0.0.0:5000 을 넣고 enter 하는 것과 같음)

여기서
LED 조정필요시 클릭
을 누른다

여기서
온, 오프, 홈으로
버튼을 눌러서 제대로 작동하는지 확인

4. 코드

ㄱ. controller.py

controller.py

from flask import request as req, Flask , render_template as rt
import RPi.GPIO as gpio
from flask import Flask

app = Flask(__name__)
LED = 14
gpio.setmode(gpio.BCM)
gpio.setup(LED, gpio.OUT, initial =gpio.LOW)

@app.route('/')
def hello():
    return rt("index.html")

@app.route("/led_home")
def led_home():
    return rt("led.html")

@app.route("/led/on")
def led_on():
    try:
        gpio.output(LED, gpio.HIGH)
        return "ok"
    except expression as identifier:
        return "fail"    

@app.route("/led/off")
def led_off():
    try:
        gpio.output(LED, gpio.LOW)
        return "ok"
    except expression as identifier:
        return "fail" 
    
if __name__ == '__main__':
        app.debug = True
        app.run(host="0.0.0.0")

ㄴ. index.html

index.html

<!DOCTYPE html>
<html>
    <head>
    <link rel="stylesheet" href="../static/style2.css">
    <style>
.title{
    text-align: center;
}
.img{
    width: 200px;
    height: 200px;
    margin-left: 25%;
    margin-top: 20%;
    display: block;
}
.text{
    margin-left: 25%;
}
    </style>
</head>
<body>
    <div class = top>
    <h1 class = "title">라즈베리 파이 모듈 컨트롤</h1> 
    </div>
    <div class = "setting">
        <a href = '/led_home' class = img><img class = "img" src = ../static/led.jpeg></a>
        <h1 class = "text">LED 조정필요시 클릭</h1>
    </div>
</body>
</html>

ㄷ. led.html

led.html

<!DOCTYPE html>
<html>
    
    <head>
        <link rel="stylesheet" href="../static/style2.css?<%=new java.util.Date()>">
        <style>
           .button_warp{
    width: 100%;
    height: 100%;
    margin : 0 auto;
    display:flex;
    justify-content: center;
    column-gap: 1rem;
    margin-top: 5%;

}

.home_btn{
    margin: 1rem auto;
    text-align: center;
}

.button-fill{
    width: 100px;
    height: 40px;
    background: dodgerblue;
    border-radius: 6px;
    color: white;
    font-size: 26px;
    transition: all .3s cubic-bezier(0.67,0.17,0.40,0.83);
    text-align: center;
}

.button-empty{
    width: 100px;
    height: 40px;
    background: rgb(99, 90, 90);
    border-radius: 6px;
    color: dodgerblue;
    font-size: 26px;
    transition: all .3s cubic-bezier(0.67,0.17,0.40,0.83);
    text-align: center;
}
.title{
    font-size:30px;
    text-align: center;
}
.on{
    text-align: center;
}

        </style>
        <script src="https://code.jquery.com/jquery-3.6.3.slim.js" integrity="sha256-DKU1CmJ8kBuEwumaLuh9Tl/6ZB6jzGOBV/5YpNE2BWc=" crossorigin="anonymous"></script>
    </head>
<body>
<div id="print"><h1>RXO AI-LAP 제 1팀장 <br>LED 센서</h1></div>
<div class="button_warp api" >
    <a>on</a>
    <a>off</a>
</div>

 <div id="result" style = "margin-top: 5%;"><h1>LED is off</h1></div>
 <div class="button-fill home_btn">홈으로</div>
</body>
<script>
    $(function(){
        console.log("웹새로고침")
        $(".api a").eq(1).trigger("click");
    })
    $(".button_warp a").click(function(){
        console.log("test")
        $(".api a").removeClass();
        $(this).addClass('button-fill');
        $(".api a").not($(this)).addClass("button-empty");
        if($(this).index() == 0) led_on();
        else                     led_off();
        
    });
	
  
    $(".home_btn").click(function(){
        console.log("click")
        location.href="/"
    });

    function led_on(){
        fetch("/led/on")
        .then(Response=> Response.text())
        .then(data => {
            let res = document.querySelector("#result");
            if (data == "ok"){
                res.innerHTML = "<h1>LED is running</h1>";
            }
            else{
                res.innerHTML = "<h1>error</h1>";
            }
        })
    }
    function led_off(){
        fetch("/led/off")
        .then(Response=> Response.text())
        .then(data => {
            let res = document.querySelector("#result");
            if (data == "ok"){
                res.innerHTML = "<h1>LED is off</h1>";
            }
            else{
                res.innerHTML = "<h1>error</h1>";
            }
        })
    }
</script>

</html>

0개의 댓글