from pyfirmata import Arduino, util
import requests, json, os
import pymysql
sql = 'select * from serial where No = '
No = 1
PIN = 13 # 아두이노 우노 LED 디지털 핀
DELAY = 1 # 1초 지연 시간
board = Arduino('COM18') # 보드 포트 번호
data = {'PIN':PIN}
headers = {"Content-Type":"application/json", 'Accept': 'text/plain'}
while True:
get = requests.post('http://localhost:3000/python',json={},headers=headers)
print(get.json())
for k,v in get.json().items():
if(v == 'ON'):
print(v)
board.digital[PIN].write(1)
elif(v == 'OFF'):
print(v)
board.digital[PIN].write(0)
이젠 nodejs설치 진행해주세요
웹상으로 제어할 겁니다.
arduino_web.js
//웹 전용
var express = require('express');
var app = express();
var bodyParser = require('body-parser')//웹 통신 허용
const request = require('request');
var port = 3000;
//아두이노 전용
let LED;
let PIN1;
//DB 전용
var mysql = require('mysql');
const { rootCertificates } = require('tls');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'mysql DB 계정',
password: 'mysql DB 패스워드',
database: 'arduino'
})
var sql = 'INSERT INTO serial(Pin,name,action)values(?,?,?)';
app.set('view engine', 'ejs'); // ejs 허용
app.use(express.static(__dirname + '/public')); //css 허용
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//get방식으로 보냄(초기화)
app.get('/', function (req, res) {
res.render('serial', {
LED: 'OFF' ,
PIN: PIN1
});
});
//post방식으로 보냄(button작동)
app.post('/', function (req, res, next) {
LED = req.body.LED;
if (LED == 'ON') {
LED = 'OFF';
res.render('serial', {
LED: 'OFF' ,
PIN: PIN1
});
} else {
LED = 'ON';
res.render('serial', {
LED: 'ON',
PIN: PIN1
});
}
console.log(LED);
//DB 보냄
connection.query(sql, [PIN1,'LED', LED], function (error) {
if (error) throw error;
});
});
app.post('/python', function (req,res) {
console.log(LED);
return res.json({name: "LED",action: LED});
});
app.post('/node', function (req,res) {
PIN1=req.body.PIN
console.log(PIN1)
return res.end();
});
app.listen(port, function () {
console.log('server on! http://localhost:' + port);
});