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框架在手机上创建应用

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

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

    关注

    28

    文章

    5043

    浏览量

    77787
  • javascript
    +关注

    关注

    0

    文章

    511

    浏览量

    53424
  • Arduino
    +关注

    关注

    184

    文章

    6428

    浏览量

    184914
收藏 人收藏

    评论

    相关推荐

    LabVIEW与Tektronix示波器实现电源测试自动化

    LabVIEW与Tektronix示波器实现电源测试自动化 在现代电子测试与测量领域,自动化测试系统的构建是提高效率和精确度的关键。本案例介绍了如何利用LabVIEW软件结合Tektronix
    发表于 12-09 20:37

    怎样用ADAU1761设计DRC的压缩/扩展?

    请问怎样用ADAU1761设计DRC的压缩/扩展。我在SigmaStudio 4.5的模块中只找到RMS。如果ADAU1761设计DRC要怎样
    发表于 11-28 06:41

    怎样用32单片机测电压?

    怎样用32单片机测电压
    发表于 10-31 07:09

    基于Arduino家庭自动化项目

    包含相关代码、详细图文、物料表一个简单的基于DIY Arduino家庭自动化项目,它使用土壤湿度传感器、泵和其他电子元件来自动浇水植物。它由一个适合室内园艺的混凝土花盆箱组成。自流式
    发表于 09-26 08:16

    PLC中怎样用X和Y两个轴走出直线轨迹?

    PLC中怎样用X和Y两个轴走出直线轨迹呢?那么这两个轴需要配合成速度成线性比例,位置和速度应该如何云运算呢?
    发表于 09-12 09:58 380次阅读
    PLC中<b class='flag-5'>怎样用</b>X和Y两个轴走出直线轨迹?

    使用Arduino Uno和SmartEdge Agile实现家庭自动化

    电子发烧友网站提供《使用Arduino Uno和SmartEdge Agile实现家庭自动化.zip》资料免费下载
    发表于 07-10 14:30 0次下载
    使用<b class='flag-5'>Arduino</b> Uno和SmartEdge Agile<b class='flag-5'>实现</b><b class='flag-5'>家庭</b><b class='flag-5'>自动化</b>

    家庭自动化系统开源构建

    电子发烧友网站提供《家庭自动化系统开源构建.zip》资料免费下载
    发表于 07-10 10:30 0次下载
    <b class='flag-5'>家庭</b><b class='flag-5'>自动化</b>系统开源构建

    Arduino UNO水族馆自动化

    电子发烧友网站提供《Arduino UNO水族馆自动化.zip》资料免费下载
    发表于 07-06 15:00 0次下载
    <b class='flag-5'>Arduino</b> UNO水族馆<b class='flag-5'>自动化</b>

    使用Arduino实现老虎机自动化

    电子发烧友网站提供《使用Arduino实现老虎机自动化.zip》资料免费下载
    发表于 07-06 11:47 0次下载
    使用<b class='flag-5'>Arduino</b><b class='flag-5'>实现</b>老虎机<b class='flag-5'>自动化</b>

    Arduino自动化园艺植物

    电子发烧友网站提供《Arduino自动化园艺植物.zip》资料免费下载
    发表于 07-06 10:43 0次下载
    <b class='flag-5'>Arduino</b><b class='flag-5'>自动化</b>园艺植物

    如何构建一个简单的家庭自动化

    电子发烧友网站提供《如何构建一个简单的家庭自动化.zip》资料免费下载
    发表于 07-05 11:41 0次下载
    如何构建一个简单的<b class='flag-5'>家庭</b><b class='flag-5'>自动化</b>

    Arduino短信自动化第1/3部分

    电子发烧友网站提供《Arduino短信自动化第1/3部分.zip》资料免费下载
    发表于 06-20 11:25 0次下载
    <b class='flag-5'>Arduino</b>短信<b class='flag-5'>自动化</b>第1/3部分

    使Arduino、继电器和蓝牙模块的家庭自动化

    电子发烧友网站提供《使Arduino、继电器和蓝牙模块的家庭自动化.zip》资料免费下载
    发表于 06-08 11:18 0次下载
    使<b class='flag-5'>Arduino</b>、继电器和蓝牙模块的<b class='flag-5'>家庭</b><b class='flag-5'>自动化</b>

    如何使用MQTT和ESP8266的家庭自动化系统 ?

    在本视频中,我们将看到在 ESP8266 上使用 MQTT 的家庭自动化系统。对于这个项目,我们将使用 Adafruit.io mqtt 服务器。 对于描述中共享的代码、原理图和 Gerber 文件链接。
    发表于 05-22 07:19

    怎样用FPGA实现FSK调制解调呢?

    最近想做这方面的,怎样用FPGA实现FSK调制解调?但是我一点头绪都没有,哪位高手帮帮忙,讲解一下什么的
    发表于 05-08 17:34