0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

怎样用Arduino和JavaScript实现家庭自动化

454398 来源:wv 2019-10-28 17:46 次阅读
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

步骤1:您需要做什么

物理的:

Arduino(此项目使用了UNO,但进行了一些调整,几乎所有开发板都可以使用)

LED(尽可能多地控制)

按钮(至少三个)

TIP41或TIP42(至少一个)

继电器(至少一个)

光敏电阻(至少一个)

温度传感器(在这个项目中,我使用了TMP36,但是很多可以很好地工作)

非物理

Arduin o IDE

Sublime Text(或您喜欢的任何文本编辑器)

Node.js

Johnny-five JS

套接字。 io

p5.js

bootstrap

我们需要设置Arduino使其与该项目正常工作,我们将看看如何

第2步:准备Arduino

您可能知道,Arduino可以处理您上传的草图为此,通常您需要在Arduino IDE上编写代码,进行编译,然后将其上传到板上,但是使用Instructable,您将在实时代码上运行,并且板上有两种获取和发布数据的方式,因此我们需要进行设置

打开您的Arduino IDE和一个名为StandardFirmata的示例,将其上传到您的开发板就可以了!您的Arduino已准备好通过JavaScript与您的计算机进行交互。

我们将首先在服务器端工作,使所有环境都可以在Arduino与浏览器之间进行交互,因此,让我们继续下一步并进行配置

第3步:从服务器准备就绪

首先,我们需要从项目专用的文件夹开始,因此,在您的命令行中为此:

mkdir myRockingProject && cd myRockingProject #name it as you want

npm init #to work with node

mkdir public #here we will put the client (browser) stuff

您可以下载我附加的package.json文件,将其放在项目文件夹中,然后在命令行中运行:

npm install

然后,创建一个名为server.js的文件,我们将所有服务器端内容放在这里,这是我们要使用的主要文件,因为这是node.js与Arduino之间的所有通信

如果您使用npm init创建了自己的package.json,我们将需要添加使我们在环境中运行良好的节点模块,所以让我们运行:

npm install --save express johnny-five socket.io

这将安装并让您使用提到的模块(表达j5和socket.io),您将能够来查看您的package.json文件的更改,包括以下内容:

“dependencies”: {

“express”: “^4.13.4”,

“johnny-five”: “^0.9.43”,

“socket.io”: “^1.4.5”

}

注意:我们目前不会使用socket.io,但我们已安装它以在发生时做好准备时间到了。

现在,在我们的server.js文件中,我们将调用要使用的模块,首先我们需要使用express,这将使我们将客户端调用路由到文件并与服务器和服务器进行交互,因此让我们创建服务器:

var express = require(‘express’); // Calling the module

var app = express(), // Creating an express ‘app’

server = app.listen(3000); // Telling the server to listen on port 3000 (localhost:3000)

app.use(express.static(‘public’)); // We tell our app (express, to serve the static files located on the ‘public’ folder

我们的服务器已准备就绪,可以监听客户端请求并向其提供信息,但是我们仍然没有任何服务

下一步是设置Arduino-服务器通信,我们将首先在服务器上对其进行设置,因此,在约翰尼五图书馆,一个功能强大的JavaScript-Arduino桥,可以直接使用JavaScript控制板,我们将设置实现自动化所需的一切!

在我们正在使用的同一文件中(server.js )我们将编写其他代码正确地在arduino IDE上写,所以让我们编写以下代码:

// Setting up johnny-five

var five = require(“johnny-five”),

arduino = five.Board();

//////////////////////////////// VARIABLES ////////////////////////////////

var living_room_light = false, other_rooms_light = false, fan = false, backyard_light = false; // Helpers

var living_room_button, other_rooms_light_button, backyard_light_button; // Buttons pins

var living_room_light_pin_led, other_rooms_light_pin_led, fan_pin, dimmable_led; // LEDs pins

var backyard_light_pin; // Relay pin

var photoresistor; // Light sensor

var temperature; // Tmp sensor

//////////////////////////////// BOARD ////////////////////////////////

arduino.on(“ready”, function() {

//////////////////////////////// DIMMABLE LED ////////////////////////////////

dimmable_led = five.Led(6);

//////////////////////////////// LIVING ROOM ////////////////////////////////

//Initialize pushbutton for living room at digital input 2

living_room_button = five.Button(2);

// Pin 13 is used to set living room light, analog input A0 is used to check light intensity from a photoresistor

photoresistor = new five.Sensor(“A0”);

living_room_light_pin_led = new five.Led(13);

living_room_light_pin_led.off();

// Check if photoresistor gets less than a half of light available and change living room light if applicable

photoresistor.on(‘change’, function() {

if(this.scaleTo([0, 100]) 《 60){

living_room_light = !living_room_light;

living_room_light_pin_led.on();

console.log(‘photoresistor-change’);

}

});

// Changes living room light when pushbutton is pushed

living_room_button.on(“release”, function () {

living_room_light = !living_room_light;

living_room_light_pin_led.toggle();

console.log(‘living-room-light-pushbutton’);

});

//////////////////////////////// OTHER ROOMS ////////////////////////////////

// All rooms excepting the living room are simultaneously light powered on manually

other_rooms_light_button = five.Button(4);

// Light is powered via pin 12, LEDs connected in parallel

other_rooms_light_pin_led = new five.Led(12);

// Change light state whenever ‘other_lights_button’ is pressed then released

other_rooms_light_button.on(“release”, function () {

other_rooms_light = !other_rooms_light;

other_rooms_light_pin_led.toggle();

console.log(‘other-rooms-change’);

});

//////////////////////////////// FAN CONTROLLING WITH TEMPERATURE MEASURING ////////////////////////////////

// Temperature will be measured with a TMP36 sensor

temperature = new five.Thermometer({

controller: “TMP36”,

pin: “A1”,

freq: 2000

});

// TIP42 transistor is attached to pin 5

fan_pin = new five.Pin(5);

// Whenever temperature provided by LM35 sensor is greater than 22° C the fan input changes its value to ‘high’ and when temperature is less or equal to 22° C it goes ‘low’

temperature.on(“data”, function () {

console.log(‘temperature: ’ + this.celsius.toFixed(2));

if(this.celsius 》 24.00) {

if(fan) {

fan_pin.high();

fan = !fan;

console.log(“Temperature is: ”+this.celsius.toFixed(2)+“, fan is on”);

}

}

else if(this.celsius 《 24.00) {

if(!fan) {

fan_pin.low();

fan = !fan;

console.log(“Temperature is: ”+this.celsius.toFixed(2)+“, fan is off”);

}

}

});

//////////////////////////////// BACKYARD LIGHT ////////////////////////////////

backyard_light_button = new five.Button(8);

// Relay to toggle the backyard light is attached to pin 9

backyard_light_pin = new five.Pin(9);

// Check any pushbutton event to toggle the light

backyard_light_button.on(“release”, function() {

backyard_light = !backyard_light;

if(backyard_light) {

backyard_light_pin.high();

console.log(“Backyard light is on”);

}

else {

backyard_light_pin.low();

console.log(“Backyard light is off”);

}

});

});

到目前为止,我们已经准备好通过服务器与arduino进行交互,我们可以构建电路,运行代码它会起作用,但是这样做的乐趣在哪里?在任何地方,电路都很棒,但是无论如何,这可指导的目的是使用Web用户界面与arduino进行交互,因此让我们继续下一步并创建我们的UI。

步骤4 :客户端(浏览器)

我们现在将使用/public文件夹,在此处,我们将添加应用程序的索引和使其动态化的JS文件,所以我们开始吧:

首先,在/lib文件夹中创建一个名为“ assets”的文件夹,并在其中另外创建两个名为“ lib”和“ styles”的文件夹,并放入bootstrap,jquery和p5文件,这些将帮助我们实现目标,引导程序看起来更平滑,p5和jquery添加自定义功能以及图表来跟踪房屋温度。

然后,在主文件夹(/public)中创建一个文件名为 index.html ,您可以根据需要检查我的并将其粘贴,并在完成可指导的自定义操作后为您自定义并玩得开心!

这是我的index.html

在拥有索引文件之后,还需要两个java脚本文件,其中一个使用jquery控制界面,另一个创建实时显示温度的图表。另外,我们现在将开始使用socket.io。

Socket.io是一个功能强大的JS库,用于构建实时Web应用程序,我们将利用它并利用它从Arduino发出事件。 -server到客户端,反之亦然,您可以在此处查看socket.io文档,并且还有许多有关如何使用它的示例。让我们继续前面提到的文件。

一个文件将称为script.js,并且需要包含以下内容:

$(function() {

var socket = io.connect(“http://localhost:3000”);

// Slider with jQuery UI

$( “#slider-range-max” ).slider({

range: “max”,

min: 0,

max: 255,

value: 0,

slide: function( event, ui ) {

// Assign the slider value to the dimmable-led input

$( “#amount” ).val( ui.value );

// Send the event to the server with the name and value of it

socket.emit(‘dimmable-led’, ui.value);

console.log(“Slider value: ” + ui.value);

}

});

$( “#amount” ).val( $( “#slider-range-max” ).slider( “value” ) );

// Both this and the next ( $(“#other-rooms-btn”).click() ) change the calling action button state and emit the event via socket

$(“#living-room-btn”).click(function() {

changeBtnState(“#living-room-btn”, “#living-room-light”);

socket.emit(‘living-room-light’, $(“#living-room-light”).val());

console.log($(“#living-room-btn”).val());

});

$(“#other-rooms-btn”).click(function() {

changeBtnState(“#other-rooms-btn”, “#other-rooms-light”);

socket.emit(‘other-rooms-lights’, $(“#other-rooms-light”).val());

console.log($(“#other-rooms-btn”).val());

});

// Checks for events sent from arduino to change the living room or every other rooms because of a pushbutton or photoresistor

socket.on(‘living-room-light-pushbutton’, function() { changeBtnState(“#living-room-btn”, “#living-room-light”) });

socket.on(‘backyard-light-change’, function(value) {

if(value) {

if($(“#backyard-light”).val() == “Off”) {

$(“#backyard-light”).val(“On”);

}

}

else if($(“#backyard-light”).val() == “On”) {

$(“#backyard-light”).val(“Off”);

}

});

///// I need to change this to handle the photoresistor only once per state /////

socket.on(‘photoresistor-change’, function() { changeBtnState(“#living-room-btn”, “#living-room-light”) });

socket.on(‘other-rooms-change’, function() { changeBtnState(“#other-rooms-btn”, “#other-rooms-light”) })

// One function to rule them all, well, the UI buttons.。.

// btn: the button id to change ------ input: the input id to change

function changeBtnState(btn, input) {

var btnClass = $(btn).attr(‘class’);

var text, state, newBtnClass, oldBtnClass;

if(btnClass === “btn btn-success”) {

oldBtnClass = ‘btn-success’;

newBtnClass = ‘btn-danger’;

text = ‘off’;

state = “On”;

} else if(btnClass === “btn btn-danger”) {

oldBtnClass = ‘btn-danger’;

newBtnClass = ‘btn-success’;

text = ‘on’;

state = “Off”;

}

$(btn).removeClass(oldBtnClass);

$(btn).addClass(newBtnClass);

$(btn).text(“Turn ” + text);

console.log(btn + “ is ” + state);

$(input).val(state);

}

});

在这里,我们正在处理UI事件(单击和一个滑块),然后它们通过套接字发出消息,这些消息将在服务器上接收并根据它们执行Arduino工作。

在另一个文件中,我们将其命名为“ temperature_canvas_sketch”借助p5.js(一个基于Processing lang的出色的JS库)显示从温度传感器获得的数据。因此,在我们的temperature_canvas_sketch.js文件中,添加以下内容:

var chartpoints = []; chartpoints.push({x: 0, y: 0});

var socket = io.connect(“http://localhost:3000”);

// Creating a canvas where the chart will be displayed and matching the connection with the socket

function setup() {

cnv = createCanvas(displayWidth / 2, displayHeight / 5);

cnv.parent(“termo-container”);

// Gets a change whenever the temperature sensor changes and sets it to its element

socket.on(‘temperature’, function(temperature) {

$(“#termometer”).val(temperature + “°C”);

createPoint(temperature);

});

}

// Handle chart points to display

function draw() {

background(255);

noFill();

stroke(0);

// Here we draw the last temperature value from the chartpoints array where it is supposed to be

//// Starts draw of point

beginShape();

for (var i=0; i 《 chartpoints.length; i++) {

var P = chartpoints[i];

vertex(P.x, height - P.y);

text(P.y, P.x, height - P.y);

//if (P.x《0)chartpoints.pop(i);

P.x--;

}

endShape();

//// Ends draw of point

}

// This function is called whenever the tmp36 sends a new value to the client

function createPoint(temp) {

//var t = random(0, height-20);

// Creates a new point with x -》 live width of the canvas & y -》 the temperature value from arduino

var P = new Points(width, temp);

chartpoints.push(P);

}

// Custom class of points that will be drawed

var Points = function()

{

var x;

var y;

var constructor = function Points(x, y)

{

this.x = x;

this.y = y;

};

return constructor;

}();

这将用来绘制带有发送数据的图表,在这种情况下,是显示房屋的实时温度。

但是现在我们在客户端而不是服务器上有了套接字,我们需要回到那里并添加它们以使其正常工作,所以继续。

步骤5:使用服务器和Arduino事件处理的套接字

现在我们在客户端拥有套接字事件处理程序/发射器,我们需要使其在服务器端工作,请记住,我们已经在第二步中安装了socket.io模块,因此我们只需要对其进行设置,就可以在server.js文件中添加以下几行:

var socket = require(‘socket.io’);

// Creating a socket

var io = socket(server);

// Retrieving client info via socket when a new connection (only one for this project) is established

io.sockets.on(‘connection’, function(socket) {

// Get dimmable light value from the UI and send it to the arduino

socket.on(‘dimmable-led’, function(value) {

console.log(‘Dimmable LED value is now: ’ + value);

dimmable_led.brightness(value);

});

// Living room and other rooms lights can be controlled via UI

socket.on(‘living-room-light’, function(state) {

console.log(‘Living room light is: ’ + state);

living_room_light_pin_led.toggle();

});

socket.on(‘other-rooms-lights’, function(val) {

other_rooms_light_pin_led.toggle();

});

});

我们现在正在处理来自客户端的事件,检索消息并使arduino对它们作出反应,使LED变暗,并打开/关闭客厅和其他房间的灯光。

在此之后,我们需要从ardu获取数据/更改时,向客户端发出事件以更改UI ino,因此在我们的arduino代码中,我们将需要添加和更改某些行。

在客厅代码中:

photoresistor.on(‘change’, function() {

if(this.scaleTo([0, 100]) 《 60){

living_room_light = !living_room_light;

living_room_light_pin_led.on();

io.sockets.emit(‘photoresistor-change’); // this is new

console.log(‘photoresistor-change’);

}

});

living_room_button.on(“release”, function () {

living_room_light = !living_room_light;

living_room_light_pin_led.toggle();

io.sockets.emit(‘living-room-light-pushbutton’, null); //this is new

console.log(‘living-room-light-pushbutton’);

});

On其他房间代码:

other_rooms_light_button.on(“release”, function () {

other_rooms_light = !other_rooms_light;

other_rooms_light_pin_led.toggle();

io.sockets.emit(‘other-rooms-change’);

console.log(‘other-rooms-change’);

});

在温度测量代码上,只需在.on(“ data”,。..)函数的回调的开头添加以下行:

io.sockets.emit(‘temperature’, this.celsius.toFixed(2));

在后院的灯光代码上:

backyard_light_button.on(“release”, function() {

backyard_light = !backyard_light;

if(backyard_light) {

backyard_light_pin.high();

console.log(“Backyard light is on”);

io.sockets.emit(‘backyard-light-change’, 1); //this is new

}

else {

backyard_light_pin.low();

console.log(“Backyard light is off”);

io.sockets.emit(‘backyard-light-change’, 0); //this is new

}

});

就是这样,我们的代码必须现在可以正常工作,转到您的命令行并运行服务器

node server

,然后在浏览器中转到http://localhost:3000,您应该看到一个UI,如图所示,该UI能够通过该UI与Arduino交互,反之亦然。

我附加了自己的script.js文件,因此您可以看一下。

步骤6:最终争论

我希望这对所有人来说都是很容易理解的,并且您会成功并运用自己。我必须说,所有显示的代码都是针对我的特定案例使用的,并且该项目最初是作为学校主题项目完成的,但是无论如何,我都试图将其应用于自己的房子(祝我好运)。随意(并且希望您会)根据需要更改代码,如果有任何疑问或疑问,可以在下面发表评论或与我联系以获取更多信息。

将来的步骤可以由您完成像这样:

添加传感器或继电器来控制更多东西,例如打开电视,冰箱,在敲门或敲钟之前就知道门口是否有人

将Arduino连接到树莓派以使本地服务器一直运行

借助一些Node.js框架在手机上创建应用

湿度传感器告诉您植物是否被水化

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 自动化
    +关注

    关注

    30

    文章

    5886

    浏览量

    89262
  • javascript
    +关注

    关注

    0

    文章

    525

    浏览量

    56003
  • Arduino
    +关注

    关注

    190

    文章

    6515

    浏览量

    195969
收藏 人收藏
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

    评论

    相关推荐
    热点推荐

    罗克韦尔自动化邀您共赴2025年自动化博览会

    11 月 17 - 20 日,作为工业自动化、信息和数字转型领域的全球领先企业之一,罗克韦尔自动化将在芝加哥举办的 2025 年自动化
    的头像 发表于 11-17 17:54 1642次阅读

    订单退款自动化接口:高效处理退款流程的技术实现

    ​  在现代电子商务系统中,订单退款是常见但繁琐的操作。手动处理退款不仅耗时,还容易出错。自动化退款接口通过API集成,能显著提升效率、减少人工干预,并确保准确性。本文将逐步介绍如何设计并实现一个
    的头像 发表于 10-21 10:41 226次阅读
    订单退款<b class='flag-5'>自动化</b>接口:高效处理退款流程的技术<b class='flag-5'>实现</b>

    使用Ansible实现大规模集群自动化部署

    当你面对1000+服务器需要部署时,你还在一台台手工操作吗?本文将揭秘如何用Ansible实现大规模集群的自动化部署,让运维效率提升10倍!
    的头像 发表于 08-27 14:41 526次阅读

    自动化计算机的功能与用途

    任务都是通过使用控制机械和流程的自动化计算机来实现自动化的。什么是自动化计算机?自动化计算机是工业级计算机,其设计坚固,能够在常规台式计算机
    的头像 发表于 07-15 16:32 532次阅读
    <b class='flag-5'>自动化</b>计算机的功能与用途

    车机交互测试自动化实现路径与案例分析

    测试设备是车机交互测试自动化实现的核心支撑,通过合理选型、部署和应用北京沃华慧通测控技术有限公司汽车测试设备,结合科学的实现路径和丰富的案例经验,能够有效提高车机交互测试的效率和质量,推动车机系统的不断优化和升级,为用户带来更加
    的头像 发表于 07-10 09:24 1177次阅读
    车机交互测试<b class='flag-5'>自动化</b><b class='flag-5'>实现</b>路径与案例分析

    机器人和自动化的未来(2)

    本文是第二届电力电子科普征文大赛的获奖作品,来自西南交通大学黄雯珂的投稿。3机器人与自动化的未来展望随着机器人和自动化技术的不断进步,未来的世界将会是一个高度自动化的世界。智能工厂、智慧家庭
    的头像 发表于 04-26 08:33 589次阅读
    机器人和<b class='flag-5'>自动化</b>的未来(2)

    HFSS 自动化建模工具

    因工作需求,自己写的HFSS参数自动化建模工具,目前只实现了常用的四种模型,可定制,如需可联系 qq:1300038043 附件下载链接:https://pan.baidu.com/s/1TVeTTFiJw-pxSyT1AT
    发表于 02-27 17:44

    环球仪器Uflex灵活自动化平台概述

    在生产厂房全面走向自动化之际,最令厂家头痛的莫过于生产线上一些难以自动化的组装工序。若以功能单一的自动化平台来解决,投资可能没有保障。环球仪器的Uflex灵活自动化平台提供一个完美的解
    的头像 发表于 02-08 09:13 964次阅读
    环球仪器Uflex灵活<b class='flag-5'>自动化</b>平台概述

    如何实现跌落式熔断器的自动化控制

    实现跌落式熔断器的自动化控制,可以通过以下技术和步骤进行: 一、技术原理 跌落式熔断器的工作原理是将熔丝穿入熔管内,当被保护线路发生故障时,故障电流使熔丝熔断,形成电弧。消弧管在电弧高温作用下分解
    的头像 发表于 02-05 10:46 1201次阅读

    自动化电桥系统的优势

    的测量能力。与传统的手动电桥相比,自动化电桥系统通过精密的电子控制和算法优化,能够实现更高的测量精度。这种高精度对于需要精确电阻值的电子元件制造、材料特性研究等领域至关重要。 2. 快速响应 自动化电桥系统的另一个显著优
    的头像 发表于 01-09 10:12 765次阅读

    基于 Docker 与 Jenkins 实现自动化部署

    前言 重塑自动化部署新高度,Docker 携手 Jenkins,在华为云 Flexus X 云服务器的加持下,引领持续集成与部署的新纪元。Flexus X 以其卓越的性能、灵活的资源配置和高效的成本
    的头像 发表于 01-07 17:25 859次阅读
    基于 Docker 与 Jenkins <b class='flag-5'>实现</b><b class='flag-5'>自动化</b>部署

    安科瑞变电站综合自动化系统选型与应用是怎样的?

    摘 要:变电站综合自动化系统是将变电站内的二次设备经过功能的组合和优化设计,利用先进的计算机技术、通信技术、信号处理技术,实现对全变电站的主要设备和输、配电线路的自动监视、测量、控制、保护、并与上级
    的头像 发表于 01-06 11:00 821次阅读
    安科瑞变电站综合<b class='flag-5'>自动化</b>系统选型与应用是<b class='flag-5'>怎样</b>的?

    Matter占用传感器强化智能家居自动化

    缝且用户友好的体验。这个DIY项目旨在展示新的智能家居连接标准Matter在实现节能家庭自动化方面的潜力。
    的头像 发表于 12-24 09:50 1093次阅读

    自动化水厂监控系统

    、保障水质安全、降低运维成本。 系统构成 自动化水厂监控系统通常由硬件设备和软件系统两部分组成。硬件设备包括传感器、控制器、执行机构、网络通信设备等,负责实时采集水厂运行数据,执行控制指令,以及实现数据的远
    的头像 发表于 12-16 16:17 1009次阅读

    自动化创建UI并解析数据

    *附件:32960_auto.rar备注:Main.vi是ui自动化2.1.vi,配置文件为32960.B.ini。 目前可以实现根据配置文件自动化创建控件并布局,且可以自动解析接收到
    发表于 12-10 08:41