IoT with JavaScript

Andrii Kucherenko
Yuriy Tkachenko

 

IoT

Hardware

Спецификация

Микроконтроллер: ATmega328

Рабочее напряжение: 5 В

Входное напряжение (рекомендуемое): 7-12 В

Входное напряжение (предельное): 6-20 В

Цифровые Входы/Выходы: 14

(6 из которых могут использоваться как выходы ШИМ)

Аналоговые входы: 6

Постоянный ток через вход/выход: 40 мА

Постоянный ток для вывода 3.3 ВЖ 50 мА

Флеш-память: 32 Кб (ATmega328) из которых 0.5 Кб используются для загрузчика

ОЗУ: 2 Кб (ATmega328)

EEPROM: 1 Кб (ATmega328)

Тактовая частота: 16 МГц

Спецификация

Микроконтроллер: ESP8266 

 Рабочее напряжение: 3.3 В 

Входное напряжение (предельное): 6-20 В

Входы/Выходы: 11

Постоянный ток через вход/выход: 40 мА

Постоянный ток для вывода 3.3 ВЖ 50 мА

Флеш-память: 64 Кб

ОЗУ: 96 Кб

Тактовая частота: 80 МГц

Беспроводной интерфейс: Wi-Fi 802.11 b/g/n 2,4 ГГц

...

void callback(char* topic, byte* payload, unsigned int length) {
  payload[length] = '\0';
  Serial.print(topic);
  Serial.print("  ");
  String strTopic = String(topic);
  String strPayload = String((char*)payload);
  Serial.println(strPayload);

  if (strTopic == "/smart-home/in/GPIO2") {
    ...
  }
  
}


void setup() {
  Serial.begin(57600);
  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  while (!client.connected()) {
    Serial.println("Connecting to MQTT broker ");
    ...
  }
}

void loop() {
  if (lastMqtt > millis()) lastMqtt = 0;
  client.loop();
 
  if (millis() > (lastMqtt + 10000)) {
    if (!client.connected()) {
      if (client.connect("smart-home")) client.subscribe("/smart-home/in/#");
    }
  }

  if (client.connected()) {
    if (celsius && celsius != -300.00) {
      client.publish("/smart-home/out/temperature", temp);
    }
    ....
  }
  lastMqtt = millis();
}

// Temperature reading from DS18B20 module
// Code is from OneWire library example
float readTemperature() {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius;
  // Can I haz an address?
  ...
}

-- a simple HTTP server
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
    conn:on("receive", function(sck, payload)
        print(payload)
        sck:send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n<h1> Hello, NodeMCU.</h1>")
    end)
    conn:on("sent", function(sck) sck:close() end)
end)
-- connect to WiFi access point
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID", "password")
-- test with cloudmqtt.com
m_dis={}
function dispatch(m,t,pl)
	if pl~=nil and m_dis[t] then
		m_dis[t](m,pl)
	end
end
function topic1func(m,pl)
	print("get1: "..pl)
end
function topic2func(m,pl)
	print("get2: "..pl)
end
m_dis["/topic1"]=topic1func
m_dis["/topic2"]=topic2func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
m=mqtt.Client("nodemcu1",60,"test","test123")
m:on("connect",function(m) 
	print("connection "..node.heap()) 
	m:subscribe("/topic1",0,function(m) print("sub done") end)
	m:subscribe("/topic2",0,function(m) print("sub done") end)
	m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0)
	end )
m:on("offline", function(conn)
    print("disconnect to broker...")
    print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
m:connect("m11.cloudmqtt.com",11214,0,1)
tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time() 
	m:publish("/topic1",pl,0,0)
	end)

Спецификация

  • GPIO: 40 пинов ;
  • USB-порты:  4 порта USB 2.0;
  • MicroSD: да.
  • Пониженное энергопотребление: разработчикам удалось снизить энергопотребление до величины 0,5-1Вт.
  • Звук: снижение уровня шумов, улучшение качества звука.
  • Улучшенный форм-фактор: разработчики сделали плату более рациональной и удобной для работы.
  • SoC Broadcom BCM2835 (CPU, GPU, DSP и SDRAM)
  • CPU: 700 МГц ARM1176JZF-S core (семейство ARM11)
  • GPU: Broadcom VideoCore IV, OpenGL ES 2.0, 1080p30 h.264/MPEG-4 AVC high-profile decoder
  • Память (SDRAM): 512 Мб
  • Видео выходы: HDMI
  • Аудио выходы: 3.5 мм джек, HDMI
  • разъем 10/100 Ethernet RJ45

Спецификация

Процессор: SoC «Tangier», включает в себя два ядра Intel Atom (Silvermont) processor (22nm) processor @ 500 MHz и 32-bit Intel Quark micro-controller @ 100 MHz
Оперативная память: 1 GB
Пользовательская память: 4 GB eMMC 
Сеть: 802.11 a/b/g/n Wi-Fi (с поддержкой 5 ГГц, чип Broadcom 43340) с встроенной антенной или внешней, и Bluetooth 4.0
USB: один разъем micro USB
Программируемые контакты:
2x UART (1 full flow control, 1 Rx/Tx)
2x I2C, 1x SPI with 2 chip selects
1x I2S
12x GPIO включая 4 контакта
ШИМ(PWM)

 

Sensors & Devices

LED

RGB LED

PUSHBUTTON

RELAY

TEMPERATURE SENSOR

PHOTO RESISTOR

DC MOTOR

SERVO

PIEZO ELEMENT

Ultrasonic Sensor

PRESSURE SENSOR

temperature-humidity sensor

Accelerometer, Gyroscope

Code

Johnny-Five

Johnny-Five is an Open Source, Firmata Protocol based, IoT and Robotics programming framework

https://github.com/rwaldron/johnny-five
http://johnny-five.io/

Cylon.js

JavaScript Robotics, By Your Command. Next generation robotics framework with support for 35 different platforms

Johnny-Five



var five = require("johnny-five");
var myBoard, myLed;

myBoard = new five.Board();

myBoard.on("ready", function() {

  myLed = new five.Led(13);

  myLed.strobe( 1000 );

  // make myLED available as "led" in REPL

  this.repl.inject({
    led: myLed
  });

  /**
   * try "on", "off", "toggle", 
   * "strobe", "stop" (stops strobing)
   */
});

Cylon.js


var Cylon = require('cylon');

Cylon.robot({
  connections: {
    arduino: { 
      adaptor: 'firmata', 
      port: '/dev/ttyACM0' 
    }
  },

  devices: {
    led: { driver: 'led', pin: 13 }
  },

  work: function(my) {
    every((1).second(), my.led.toggle);
  }
}).start();

Cylon.js


var Cylon = require('cylon');

Cylon.robot({
  connections: {
    arduino: { 
      adaptor: 'raspi' 
    }
  },

  devices: {
    led: { driver: 'led', pin: 13 }
  },

  work: function(my) {
    every((1).second(), my.led.toggle);
  }
}).start();

Johnny-Five



var five = require("johnny-five");
var raspi = require('raspi-io');

var myBoard, myLed;

myBoard = new five.Board({io: new raspi()});

myBoard.on("ready", function() {

  myLed = new five.Led(13);

  myLed.strobe( 1000 );

  // make myLED available as "led" in REPL

  this.repl.inject({
    led: myLed
  });

  /**
   * try "on", "off", "toggle", 
   * "strobe", "stop" (stops strobing)
   */
});

Flower Pot

Flower Pot

var board = new five.Board({
  io: new raspi()
});

io.on('connection', function(socket) {
  socket.on('start.servo', function() {
    servo.to(110);
    setTimeout(function() {
      servo.to(10);
    }, 1000);
  });

  sensor = {
    initialize: function() {
      return sensorLib.initialize(22, 4);
    },
    read: function() {
      var readout = sensorLib.read();
      console.log('Temperature: ' + readout.temperature.toFixed(2) + 'C, ' +
        'humidity: ' + readout.humidity.toFixed(2) + '%');

      socket.emit('data.update', {
        temp: readout.temperature.toFixed(2),
        hum: readout.humidity.toFixed(2)
      });
      setTimeout(function() {
        sensor.read();
      }, 1000);
    }
  };
  sensor.initialize();
  sensor.read();
});
var Cylon = require('cylon');
var LIMIT = 25;
Cylon.robot({
  connections: {
    server: { adaptor: 'mqtt', host: 'mqtt://localhost:1883' },
    raspi: { adaptor: 'raspi' }
  },

  devices: {
    bmp180: { driver: 'bmp180' },
    servo: { driver: 'servo', pin: 3 }
  },

  work: function(my) {
     my.bmp180.getTemperature(function(err, temperature) {
      if (err) {
        console.log(err);
        return;
      }
      my.server.publish('smart-house/temperature', temperature);
      if (temperature > LIMIT) {
       my.servo.angle(100);
      }
    });

  }
}).start();

Question?

IoT with JavaScript

By Andrey Kucherenko

IoT with JavaScript

  • 1,871