본문 바로가기
전자공학/MCU

[아두이노]Serial 통신3-1

by 17Hyuk 2022. 5. 8.

이번편은 번외편으로 변경 가능한 부분을 setting.json을 통해서 유지보수 하기 쉽도록 했다.

json이란 txt 처럼 데이터 포맷이다.

입력방식은 파이썬에서 dict와 유사하다고 생각하면 된다.

 

setting.json

{
"server_port": "5000",
"arduino_port": "COM4",
"baudrate": "9600"
}

 

위에 setting.json 이라는 파일은 이런식으로 읽을 수 있다.

import json
path = "./setting.json"
with open(path, 'r', encoding='utf-8') as json_file:
    json_data = json.load(json_file)
print(json_data)
print(type(json_data))

 

 

 

결과

즉, json 데이터는 dict 타입으로 저장이 된다.

 

우선 귀찮으면 소스코드를 다운받으면 된다.

LED.zip
0.00MB

 

이것을 응용해서

 

app.py

from flask import Flask, render_template, request
import serial
import json
with open('./setting.json', 'r', encoding='utf-8') as json_file:
    setting_data = json.load(json_file)

app = Flask(__name__)


# input값을 길이 32로 만들어줌
# ex) 51001100 -> 51001100!!!!!!!!!!!!!!!!!!!!!!!! (! 는 아두이노에서 continue 처리)
def len32(tx):
    return str(tx) + ''.join(list('!' for i in range(32-len(tx))))


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

@app.route('/LED_ctrl/', methods=['post'])
def LED_ctrl():
    py_serial = serial.Serial(
        port=setting_data['arduino_port'],    #본인에게 맞는 포트 설정해주기
        baudrate=int(setting_data['baudrate']),
    )
    command = request.form['command']    
    serial_flag = 0
    rx_result = ''

    while True:
        if py_serial.readable():
            rx = py_serial.readline()[:-1].decode()
            print(rx)
            rx_result = rx_result + rx + '\n'

        # 명령어 전송
        if serial_flag==0 :
            tx = len32(command)
            py_serial.write(tx.encode())
            serial_flag = 1

        if rx[0:9] == 'Complete!':
            break
    return render_template('index.html', result = rx_result)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=int(setting_data['server_port']), debug=True)

 

3편에서의 app.py를 setting.json 파일을 읽은 후 setting_data 변수에 넣어서

유지보수 하기 쉽도록 만들었다.

'전자공학 > MCU' 카테고리의 다른 글

[EPS32] TCP통신1  (0) 2022.06.17
[아두이노] 아두이노간 Serial 통신1  (0) 2022.05.08
[아두이노]Serial 통신3 (Flask 활용)  (0) 2022.05.08
[아두이노] Serial 통신2  (0) 2022.05.07
[아두이노] Serial 통신1  (0) 2022.05.07

댓글