[思路]:树莓派安装express服务器,访问服务器,与服务器交互,从而控制硬件,最终实现树莓派引脚电平控制,进而实现与树莓派电路板引脚相连的LED亮与灭。
ExpressJs: Fast, unopinionated, minimalist web framework for Node.js http://expressjs.com/
树莓派:
Raspberry Pi 4: Your tiny, dual-display, desktop computer https://www.raspberrypi.org/
树莓派上安装node运行时的方法,此处不表。先给出总体程序架构:
1. lotBerry:.//根目录
2. │app.js //服务器主脚本程序
3. │package.json //程序配置
4. │
5. ├─node_modules//所必需依赖库存储位置
6. └─views//存储
7. about.html// 关于页面
8. error.html// 错误页面
9. index.html// 主页面
使用npm init命令生成配置文件package.json,安装必要包,命令行如下所示:
1. npminstall express --save //安装express框架
2. npminstall ejs --save //网络模板渲染
3. npminstall body-parser --save//网页相关数据解析
此时package包内容如下:
1. {
2. "name": "lotberry",
3. "version":"1.0.0",
4. "description":"",
5. "main": "app.js",
6. "scripts":{
7. "test": "start"
8. },
9. "author":"",
10. "license":"ISC",
11. "dependencies":{
12. "body-parser":"^1.18.3",
13. "ejs": "^2.6.1",
14. "express":"^4.16.4"
15. }
16.}
基于Express的服务器逻辑app.js如下:
代码语言:javascript复制var express = require("express");
var ejs = require('ejs'); //视图处理的模块
var app = express();
var bodyParser = require('body-parser');//处理JSON,URL编码的等数据
var path = require('path');
var urlencodedParser = bodyParser.urlencoded({ extended: false });////编码解析
app.use(express.static('public'));//
app.set('views',path.join(__dirname, '/views'));//网页模板存放位置
app.set('view engine', 'ejs');//
app.engine('html', ejs.renderFile);//
app.get('/', function(req, res){//
let checked='';
if(Math.random()>0.5) checked='checked';//初始化页面中的复选框
res.render('index.html',{title:'开关量示意',checked:checked});
});
app.post('/doVerb_post', urlencodedParser, function (req, res) {//
var response = {"tips":req.body.tips,"led":req.body.Led_Switch};
if(req.body.Led_Switch){
console.log("复选框处于选取状态");
}else{
console.log("复选框未选取");
}
res.end(JSON.stringify(response));//页面显示提交状态的JSON结果
});
app.get('/about', function(req, res){//获取关于页面
res.render('about.html');
});
var server = app.listen(8000, function(){//服务器运行并监听端口8000
console.log("服务器已启动8000端口,请在浏览器打开 http://localhost:8000");
});
服务器搭建好了,响应页面index.html根据bootstrap简单编制如下:
代码语言:javascript复制<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/css/bootstrap3/bootstrap-switch.min.css">
<title>Hello, world!</title>
</head>
<body>
<nav class="navbar navbar-expand-sm navbar-dark bg-dark">
<a class="navbar-brand" href="#">物联网</a>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">操作页面 <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">关于/About</a>
</li>
</ul>
<form class="form-inline ml-auto">
<a href="{% url 'login' %}" class="btn btn-outline-secondary">登录</a>
<a href="{% url 'signup' %}" class="btn btn-primary ml-2">注册</a>
</form>
</div>
</nav>
<div class="container-fluid">
<h6>物联网示例:通过网络控制LED亮与灭</h6>
<form action="http://127.0.0.1:8000/doVerb_post" method="POST">
<div class="form-group">
<div class="form-group form-check">
<input type="checkbox" <%= checked %> name="Led_Switch"/>
<label class="form-check-label" for="led-Led_Switch">点击选择打开或者关闭</label>
</div>
<label for="tipsInput">备注:</label>
<input type="text" class="form-control" id="tipsInput" name="tips" placeholder="输入备注">
<small class="form-text text-muted">输入备注(示例)</small>
</div>
<button type="submit" class="btn btn-primary">确认提交</button>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/js/bootstrap-switch.min.js"></script>
<script>
$("[name='Led_Switch']").bootstrapSwitch({ onText : "打开",offText : "关闭",})
</script>
</body>
</html>
此时在局域网就可以与服务器响应了,例如我们在WIN10上模拟终端网页运行界面:
此时,还不能控制树莓派引脚,我们引入rpio库,用于控制树莓派IO端口的电平高低,首先安装该包:
1. npminstall rpio -save
将上述app.js中post逻辑如下修改:
代码语言:javascript复制var rpio = require('rpio');
rpio.open(12, rpio.OUTPUT,rpio.LOW); //第12引脚,设置为输出,设置输出低电平
rpio.write(12, rpio.HIGH); //输出高电平,点亮LED
app.post('/doVerb_post', urlencodedParser, function (req, res) {//
var response = {"tips":req.body.tips,"led":req.body.Led_Switch};
let rpio = require('rpio');
rpio.open(12, rpio.OUTPUT,rpio.LOW); //第12引脚,设置为输出,设置输出低电平
if(req.body.Led_Switch){
console.log("复选框处于选取状态,即将点亮LED");
rpio.write(12, rpio.HIGH); //输出高电平,点亮LED
}else{
console.log("复选框未选取,即将关闭LED");
rpio.write(12, rpio.LOW); //输出高电平,点亮LED
}
res.end(JSON.stringify(response));//页面显示提交状态的JSON结果
});
运行效果示意如下:
点亮LED所需电流相对较小,如要定时开启大功率电力设备,GPIO的驱动电流就远不能满足要求了,这时需要配合继电器实现大功率电器开启关闭。