Espruino pico: програмирование usb-микроконтроллера на javascript

Подключение к компьютеру и питание Iskra JS

Стандартное подключение устройства к компьютеру производится через micro-USB кабель. Однако, имеется возможность установить дополнительный модуль беспроводной связи и удалённо подключаться к компьютеру. Подсоединение Iskra JS к среде разработки может использоваться не только для программирования, но и для использования в качестве HID-устройства. Соединение через micro-USB защищено предохранителями, разрывающими связь с компьютером при превышении входящего тока грани 500 мА. Это обезопасит устройство от перегорания.

Iskra JS оснащена собственным 2.1 мм разъёмом для подключения к электрической сети. Подключение питания к USB или разъёму определяется в автоматическом режиме. Для питания через 2.1 мм гнездо рекомендуется использовать входящее напряжение 7-15 В. Выходящее напряжение для питания дополнительных модулей преобразуется до 5 и 3.3 вольт соответственно. В качестве альтернативного источника питания доступны портативные аккумуляторы. Система Iskra JS на переносном аккумуляторе отличается автономностью и широкой вариативностью для использования.

Габариты устройства

Амперка тщательно продумала габариты Iskra JS, добавив возможность крепления к поверхности. Как и в Arduino, дополнительные модули присоединяются подобно «бутерброду», размещаясь друг на друге. Главная плата получила отверстия для шурупов, позволяющие зафиксировать готовое устройство на поверхности или с другим изделием. Размер платы составляет 69×53 мм, но USB-порт и разъём для питания выпирает из корпуса на несколько миллиметров.

Features

  • Bluetooth Low Energy
  • Espruino JavaScript interpreter pre-installed
  • nRF52832 SoC — 64MHz ARM Cortex M4, 64kB RAM, 512kB Flash
  • ABS plastic rear case with lanyard mount
  • Silicone cover with tactile button
  • IR Transmitter
  • Built in thermometer, light and battery level sensors
  • Red, Green and Blue LEDs
  • NFC tag programmable from JavaScript
  • Pin capable of capacitive sensing
  • Weight: 14g in plastic case, 20g in packaging
  • Dimensions of cardboard box: 64mm x 62mm x 16mm
  • Dimensions of plastic case: 36mm dia, 12.5mm thick
  • Dimensions of bare PCB: 29mm dia, 9mm thick
Features Puck.js v1 Puck.js v2
0.1″ GPIO 8 7
SMD GPIO 9 2
Magnetometer MAG3110 LIS3MDLTR
Accelerometer No LSM6DS3TR-C
Gyro No LSM6DS3TR-C
Temperature Sensor nRF52 (uncalibrated) PCT2075TP (calibrated)
MOSFET Output No 1x

How is Espruino different to Arduino / Raspberry Pi / Embedded Linux?

Espruino vs Raspberry Pi / Embedded Linux boards

  • Raspberry Pis are very powerful and flexible, but have a relatively high power consumption in idle, making it difficult to run them off a battery. Raspberry Pi is ~50mA minimum when idling, Puck.js is 0.003mA.
  • You can’t reliably schedule actions in real-time on a Raspberry Pi which makes accurate timing difficult
  • Raspberry Pis are good at Video, which Espruino isn’t powerful enough to support.
  • Espruino runs JavaScript: this makes it very approachable and easy for beginners. Raspberry Pi on the other hand gives you a choice of programming languages, which is powerful — but can be daunting.
  • Raspberry Pi lacks Analog IO, which is supported by Espruino.
  • Raspberry Pi requires an SD card containing the operating system (which Espruino doesn’t).

Espruino v Arduino

  • Espruinos are smaller than most Arduino boards and are much easier to get started with.
  • You don’t have to pre-install software on your Mac or PC.
  • While Arduino has low power consumption, the Espruino board is designed with efficiency in mind and draws over 10x less power when sleeping.
  • The use of a JavaScript interpreter means Espruino doesn’t have to be reset when you make changes to the code, however it also means that the execution speed will be slightly slower.

Работа с интерфейсом 1-Wire

Отработка нажатий на встроенную кнопку

Прочитать состояние кнопки позволяет функция digitalRead():

1
2

>digitalRead(BTN)

=

Мониторить состояние кнопки можно, периодически считывая ее состояние с помощью setInterval(), однако более корректным будет использование функции watch():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

clearWatch();// Удалить старые триггеры (если были)

setWatch(// Задать новый триггер (watch)

function(e){// Callback при срабатывании триггера

// e.state — состояние кнопки

digitalPulse(LED1,1,50);

},

BTN,// Мониторим состояние встроенной кнопки

{// Параметры триггера

repeattrue,// Мониторить многократно

debounce50,// Предотвращение дребезга контактов (в миллисекундах)

// edge: «rising»,  // Срабатывать только при нажатии

// edge: «falling», // Срабатывать только при отпускании

edge»both»,// Срабатывать как при нажатии, так и при отпускании

}

);

Для Windows

Подготовка софта

  1. Скачайте и установите на компьютер программу для прошивки микроконтроллеров STM32.

Наеобходимо устанавливать программу прямо на диск C:/. Если в пути до этой программы будут кириллические символы или пробелы, то программа будет работать с ошибкой.

  1. Отключите плату от компьютера
  2. Зайдите в «Диспетчер устройств»
  3. Переключите управляющую платформу в DFU-режим. Для этого необходимо соединить пин с пином .
    1. Для платформы Iskra JS замкните эти два контакта джампером.

      Не снимайте с платы Iskra JS , иначе на плату не поступит питание. Если у вас набор Йодо, возьмите временно джампер с платы Troyka Slot Shield

    2. Для платформы Iskra JS Mini замкните пины с пином с помощью провода «мама-мама»

  4. Подключите плату к компьютеру и посмотрите как определяется платформа:
    1. плата определилась во вкладке и без восклицательного знака. Смело можете переходить к запуску программы DfuSe.
    2. плата определилась во вкладке и c восклицательным знаком.

    3. плата определилась во вкладке .В последних двух случаях необходимо

Установка драйвера для STM32 в DFU-режиме

  1. Зайдите в «Диспетчер устройств».
  2. Выделите «неработающее устройство» и нажмите кнопку «обновить драйверы».

  3. Выберите пункт «Поиск и установка драйверов вручную»

  4. Укажите путь к драйверу:
    1. для 32-х битных систем:

    2. для 64-х битных систем:

  5. Должно появиться окошко об успешном завершении установки драйвера.

  6. В итоге драйвер для USB-интерфейса микроконтроллера STM32 в DFU-режиме, должен находиться во вкладке «контроллеры USB» и без восклицательного знака.

Всё получилось. Теперь можно продолжить «обновлять прошивку в DFU-режиме»

Обновление прошивки

  1. Скачайте прошивку в зависимости от вашей управляющей платформы:
    1. прошивка для Iskra JS

    2. прошивка для Iskra JS Mini

  2. Распакуйте ZIP-архив. Распаковывать его лучше всего в корень диска C. Если в пути до архива будут русские буквы или пробелы, то программа работать не будет.

  3. Запустите программу DfuSe.

  4. Выберите DFU-файл прошивки, кнопкой .

  5. При успешном выбранном файле, увидите надпись

  6. Нажмите на кнопку для начала прошивки платы.

  7. В итоге должны увидеть сообщение .

Это значит всё получилось. Жмём «Quit», снимаем перемычку с и перезагружаем плату.

Далее запускайте Espruino Web IDE и попробуйте

Frequently Asked Questions

Why don’t modules work when typing on the left-hand side of the Web IDE (or from a terminal window)?

When you type on the right-hand side and click Send to Espruino, the Espruino Web IDE scans your code for statements and loads the relevant modules off the internet. Because the left-hand side of the Web IDE (or a terminal window) sends each character direct to Espruino, by the time you have pressed enter to execute your command, it’s then too late to load the module.

Instead, Espruino defaults to what is mentioned under the Stand-alone Espruino heading above — it looks on an SD card (if inserted) for the module. This is why you might get a error written to the console.

If I load modules from an SD card, will the SD card always need to be inserted?

No. As long as you have used at least once for each module before you type , all the information that is needed will be cached inside Espruino.

Can I dynamically load (and unload) modules?

Yes. By default each module that is loaded will be cached (to avoid loading modules twice). However you can call which will remove the module from the cache and free the memory that it uses.

Saving code to flash

With the implementation of buildin module Storge it’s simple to store any type of object you can think of.

Currently 16KB for 512KB ESPs and 192KB for 4MB ESPs of flash are reserved to save JS code
to flash using the save() function. The total JS memory is larger (22400 bytes) so if you
filled up the JSvars you will need compression to work well. Some simple
tests show that «it should fit» but it’s certainly possible that some
combinations of stuff doesn’t. In that case you’re a bit out of luck.

If the save() area contains something that crashes Espruino or otherwise
doesn’t let you reset the system you can disable whatever is saved by
flashing blank.bin to the last 4KB block of the save area (0x7A000).

Client

HTTP clients are like Web browsers — they request a webpage from (or submit information to) a web server.

For a simple HTTP client just use . Note that as the data from the webpage is sent in packets, you must register a handler to deal with each bit of data as it arrives.

The example below will just output the contents of the Espruino website:

You can also handle the event so that you can process with the contents of the webpage in one go — be careful you don’t run out of RAM for larger webpages though!

Handling Errors

returns an instance of which will emit an event if there are problems connecting.

This means you can trap connection errors with something like the following:

Tutorials

Tutorials using the Pico Board:

Storing HTTPS Certificates
GNSS Espruino Position Tracker
Espruino ISS Notifier
Quick Start (Writing Code)
Espruino Web IDE
Handling POSTed data from Forms
Quick Start (USB)
Flappy Bird Game
Low-level STM32 Peripheral access
Advanced Debug
Pico Clock
Arduino Pico adaptor board
Espruino Home Computer
Snake Game
5 Minute Wire Loop Game
Pico Weather Station
Pico LCD Display Hello World
Pico Electronic Dice
Controlling Pico from a Computer
AA/AAA Battery Charger
Image Slideshow with ILI9341 display
Interactive Web-based UI
Logging to Google Sheets
Slot Machine
Pico Vibration
Pico Piano
Pico Light Sensor
Pico Infrared Transmit and Receive
Pico FET Output
Pico Buttons

Start writing code!

Please try the walkthrough to get started writing
your first code for Espruino

Now you’ve got an idea how to use Espruino:

  • Have a look at the Tutorials and Reference pages
  • Check out Modules to see which libraries of code are available to use
  • If you have a Pico, WiFi or Original Espruino board then click those links for more in-depth information about your board, as well as for links to tutorials that specifically use your board.
  • See how to use the more advanced features of the Web IDE
  • Check out other ways of Programming Espruino
  • Instantly Search all the Espruino website’s documentation (using the box in the top right)
  • If you’ve got a question, please check out our Forum

Power, and the FET/B0 Jumper

Pico Board Quick Reference Circuit Diagram (below) Description
USB Plug VUSB USB voltage in
VCC 5V 5V USB voltage output (minus diode drop) if connected, Battery voltage if not
Bat (also pad marked ) BAT_IN VBAT Battery voltage input (connect battery here)
3.3V VDD VDD Regulated 3.3v output (~200mA continuous)

Currently the labelling for the Pico’s pins is quite confusing (it’s different on the circuit diagram, PCB silkscreen, and the Pinout diagram). Hopefully the table above will help to clear it up slightly.

Espruino’s power circuitry is as above. When USB is connected the device is powered through a Schottky diode with 0.3v voltage drop. However when USB is disconnected then Espruino can be powered from a battery with no voltage drop. This is done by turning on the PFET Q1.

However, the Jumper allows you to connect the PFET’s gate to pin B0. This allows you to do several things:

  • Check whether the device is running from USB or Battery ()
  • When running from USB, use the Pin as a powered 5V output.
  • When running from USB with a battery connected, charge the battery.

This last reason is why the jumper is disconnected by default. It could be dangerous to charge a LiPo battery this way unless your software also monitor’s the battery’s charge.

Once the Jumper is shorted, the following commands will work:

The jumper can be shorted by scribbling over it with a normal HB pencil. See the Pico FET Output tutorial for an example.

Flash map and access

Note: if you are looking for a free flash area to use, call ,
which will return a list of available areas (see docs).

The esp8266 modules come with varying flash chip
sizes. The flash layout for each size is slightly different. There are
a number of random tidbits to know about flash layout:

  • There are two binary formats in use: the non-OTA and the OTA update
    format. The non-OTA has no 2nd stage bootloader, starts at 0x0000 in
    flash, and has two binary blobs: one for data and one for instructions (+
    read-only data). The OTA format has a 2nd stage bootloader at 0x0000 and
    then a single binary blob for the first firmware image at 0x1000. There
    is a 2nd binary blob up after the first one to provide the two firmware
    images necessary for a safe OTA update. All this is described in the
    Espressif IOT SDK User Manual.
  • The hardware can memory-map 1MBytes of flash, but it has to be read
    on word (4-byte) boundaries, it cannot be written using the memory map.
  • Every flash layout has a 16KB «system param» area in which the
    SDK stores settings, including RF parameters and wifi settings
  • The Espruino firmware uses over 400KB, which is far more than fits into
    an OTA-capable flash layout on modules that have only 512KB of flash.
    Therefore Over-The-Air upgrades of the Espruino firmware cannot be supported
    on these modules.

In order to produce a single flash image for all esp8266 modules some
trickery has been used. The key concepts are:

  • All modules use the OTA firmware format with a second-stage bootloader
    and the two binary images allowing for upgrades (these are called user1.bin
    and user2.bin by Espressif).
  • On modules with 1MB of flash or more the standard OTA flash layout is used
    with two 512KB application partitions. On modules with more than 1MB of flash,
    the flash beyond 1MB can be used for a forthcoming spiffs filesystem.
  • On modules with 512KB of flash, a somewhat tricked layout is used. The SDK
    is told to use an OTA layout with two 256KB firmwares but in fact a single 400KB+
    firmware is loaded and care is used not to conflict with the 2x256KB layout.

The result of all this is the following:

Start Start Length Function
0x000000 4KB Bootloader with flash type/size header
0x001000 4KB 468KB Espruino firmware, first partition
0x076000 472KB 4KB SDK RF calibration save area on 512KB modules
0x077000 476KB 4KB EEPROM emulation
0x078000 480KB 12KB Espruino save() area
0x07B000 492KB 4KB Espruino system and wifi settings
0x07C000 496KB 16KB 512KB flash: Espressif SDK system params, else unused
0x080000 512KB 4KB SDK RF calibration save area on 1MB and larger modules
0x081000 516KB 472KB Espruino firmware, second partition
0x0F7000 988KB 4KB Unused
0x0F8000 992KB 16KB Unused
0x0FC000 996KB 16KB 1MB flash: Espressif SDK system params, else unused
0x100000 1MB approx 1MB-3MB flash unused on 2MB-4MB modules
0x1FC000 2032KB 16KB 2MB flash: Espressif SDK system params, else unused
0x3FC000 4080KB 16KB 4MB flash: Espressif SDK system params, else unused

The Espressif SDK system params area is composed of:

Offset Size Function
0x0000 4KB RF parameter values (default in esp_init_data_default.bin)
0x1000 4KB ?
0x2000 4KB Wifi and other system parameters (clear using blank.bin)
0x3000 4KB ?

Note that the SDK RF calibration save area was added with SDK1.5.4 patch 1.
The library provides a function that returns an array of free flash areas should you want to
use the EEPROM emulation class or read/write flash directly.

Examples

Tilt Hydrometer Repeater
Tilt Hydrometer Brew Display with Pixl.js
Dinosaur Game
Asteroids Game
WiFi Websocket Server
Pixl.js Wireless Weather Station
Pixl.js Pong Game
Pixl.js Multiplayer Pong Game
Morphing 7 Segment Clock
Pixl.js Wireless Temperature Display
Pixl.js Bluetooth to Ethernet MQTT Bridge
Wifi Remote Console
Pixl.js Spectrum Analyser
Pixl.js Oscilloscope
Pixl.js Clock
Animal Guessing Game
Platform Game
Pixl.js Temperature Display
Pixl.js Menus
Pixl.js Conference Badge — Rotating Cube
WiFi Xively Humidity/Temperature Sensor with Display
Image Slideshow with ILI9341 display
Simple Data Logger
The Useless Box — a box that turns itself off
Distance Sensing Robot
UI Example — Slider for Pixl.js
UI Example — Slider
UI Example — Radio Buttons for Pixl.js
UI Example — Radio Buttons
UI Example — Keyboard
UI Example — Bitmap fonts
UI Example — Checkbox on Pixl.js
UI Example — Checkbox
UI Example — Buttons on Pixl.js
UI Example — Buttons
UI Example — all ui elements on Pixl.js
UI Example — ui control w/ physical push buttons
Open Weather Map Example
Temperature Graph on a PCD8544 display, with DS18B20 temperature sensor
Temperature on a PCD8544 display, with DS18B20 temperature sensor
Reaction Timer using RGB123
HTTP Image Loader
LED Clock (using WS8111)
Remote Control Helicopter with Wii Nunchuck
LED Volume (VU) Meter
Running code from an EEPROM
HTTP File Server

MORE INFORMATION

OLIMEXINO-STM32

Good value, and can usually be purchased from well-known suppliers. It contains an SD card, Arduino-style headers, and conveniently a LiPo battery connector (with charger).

It comes pre-flashed with a bootloader. HOWEVER there is not enough space for this and Espruino, so you will need to overwrite it using a USB-TTL converter. See Serial Bootloader for instructions.

You can get this directly from Olimex or Farnell/Element14.

‘HY’ LCD Modules

These appear to come from Haoyu electronics and come in a few types, with varying LCD sizes. They are amazingly good value, and can be obtained from eBay (although they are often shipped direct from Hong Kong or China). They don’t generally have a specific name or model number, so are hard to tell apart.

Espruino contains bitmap and vector fonts, and along with the SD card driver and space for saving variables Espruino starts to have trouble fitting in just 128kb of Flash — so we suggest that you avoid the RBT6-based board and head for the VET6 or VCT6 ones.

2.4″ STM32F103VET6 — 512kb Flash, 64kb RAM — The largest board, but with the most features — 4 buttons, 4 LEDs, 2 Potentiometers, 2x USB, an RS232-level serial connection, SD card, buzzer, and a external flash chip. Has ‘HY-STM32_100P’ on the back of the PCB. BEWARE: There is a new version of this board that is wired up differently — Espruino will only drive the LCD on the original board.

2.8″ STM32F103VET6 — 256kb Flash, 48kb RAM — This looks just like the 2.4″ STM32F103VET6, but is UNTESTED (May work with 2.4″ drivers)

2.8″ STM32F103RBT6 — 128kb Flash, 20kb RAM — This works, however the board itself very basic with few peripherals, the CPU does not have much flash memory, and it is not recommended. RBT6 does not support the faster FSMC LCD interface, so LCD updates are slow. SD card is currently unimplemented. Has MINI-STM32-V3.0 on the main board under the LCD. BEWARE: Boards with an SD card and ‘armjishu.com’ written on the bottom are currently unsupported.

3.2″ STM32F103VCT6 — 256kb Flash, 48kb RAM — Works well. It has a big display and it is quite fast. Few on-board peripherals though (2 LEDs, 2 Buttons and an SD card). Recommended.

3.2″ STM32F103RBT6 — 128kb Flash, 20kb RAM — UNTESTED (May work with 2.8″ drivers)

Connection Types

USB

Many Espruino boards have a USB connector, and when you plug this into
your PC the board appears as a USB Serial device, which you can then connect
to.

This is what we’d suggest programming Espruino devices with.

NOTE: Pixl.js is an exception here — is has a USB connector but it is for
charging only.

Bluetooth LE

Puck.js and other Espruino Bluetooth devices present themselves as as
Bluetooth LE ‘Nordic UART’ device, and can be connected to and programmed through
that. It’s the suggested method of connection for Puck.js.

Adafruit make a Bluetooth LE UART board
that can be used to add Bluetooth LE UART capability to other Espruino devices.

Serial / UART

When not connected to a computer by USB, Espruino boards usually open up a serial
port on two of their pins at 9600 baud so that they can be programmed via Serial.
The pins used for this are detailed in the Pinout section of your board’s specific
reference page (eg , where they’re marked with ).

NOTE: ESP32 and ESP8266 devices use 115200 baud
for serial, not the 9600 that every other Espruino does.

To save power, Puck.js and other Bluetooth Espruinos only power up
the serial port if they detect a voltage on the RX pin at boot time.
See

Bluetooth UART

The Original Espruino Board has a footprint on the back for
an HC-05/HC-06 Bluetooth Module. Once soldered, it uses the
standard Serial port (detailed above) for communication. For more information
see here.

Standard Bluetooth is not the same as Bluetooth LE, and can’t be used to
communicate from a Website.

WiFi/Ethernet

Currently Espruino boards don’t come with Telnet support out of the box.
If you’re running Espruino on an ESP8266 then Telnet is
enabled.

On other boards, once you have a network connection established you can run:

However, using will break your connection.

Is there a delay() function in Espruino?

There’s which will execute a callback
function after a certain time period, and there is also
hich can be used to send carefully timed pulses.

An actual delay function isn’t implemented because it encourages you to write code
that causes problems for Espruino. As Espruino doesn’t have preemptive multitasking,
other tasks cannot execute until the current task has finished.

If you make your current task take a long time to execute then it will probably
cause problems elsewhere — if serial data or pin changes can’t be processed in
a sensible time period, the input buffers might overflow and data will be lost.

You can still delay your code quite easily using ,
but you should seriously consider re-writing your code to use
and/or — the end result will be a much faster, more efficient piece of code.

Turning Puck.js on

Puck.js is either supplied with a separate battery, or assembled with the
battery inside and a clear plastic tab between the battery
and PCB to keep it turned off. To turn it on, you need to:

  • Pull the silicone case off the top,
  • Tip the PCB out
  • If a battery is installed, push it out from the back with a blunt object and make sure the clear plastic tab is removed
  • Push the battery back in, with the side of the battery (with the writing on)
    facing away from the Puck.js PCB:

  • As the battery is inserted the red LED should flash once, very briefly.
  • If the green LED lights or red stays lit, it is because you have accidentally
    pressed the button down while inserting the battery. Remove the battery and try
    again, making sure the button next to the battery connector isn’t pressed.
  • Reassemble (note that the battery should be facing the black plastic case,
    and the button (next to the battery) should be positioned as far away from
    the ‘step’ in the case as possible:

Note: Do not re-fit the PCB upside-down or force it into the case. If
positioned correctly it should slide in. Forcing the PCB or fitting it
upside-down could damage the aerial which will stop Puck.js’s Bluetooth
from working correctly.

Advanced Reflashing

In very rare cases (if you are experimenting with writing to Flash Memory), you may be able to damage the bootloader, which will effecitively ‘brick’ the Pico.

To fix this, you’ll have to use the hard-wired USB DFU (Device Firmware Upgrade) bootloader. You can also use this method for flashing non-Espruino firmwares to Espruino.

Just:

  • Short out the solder jumper on the back of the board — you can do this by drawing over it with a pencil.
  • Install ST’s DFU utility on Windows, or dfu-util for Mac or Linux
  • Download the latest Espruino Pico binary from espruino.com/binaries
  • Hold down the Pico’s button while plugging it into USB
  • Use the DFU tool to flash the firmware. Using the GUI on windows, or with the command for on Mac/Linux.
  • Un-short the jumper to re-use the original Espruino Bootloader. If you used a Pencil mark then you may need to use cleaning fluid and a small brush to totally clear out the graphite.

Note: If you can’t access the bottom side of the board (maybe it is soldered down), on rev 1v3 boards BOOT0 is available via a gold teardrop-shaped pad on the top of the board. Short this to 3.3v while applying power to enable DFU mode (holding down the button is then not required).

Serial Console

When power is first applied, Puck.js checks if pin is at 3.3v (which will be the
case if it is connected to a Serial port’s transmit line). If it is, it initialises
the on-chip UART on (Puck.js RX) and (Puck.js TX) and puts the Espruino
console (REPL) on it at 9600 baud.

To use it, connect to a 3.3v output USB to TTL converter as follows:

Puck.js USB->TTL converter
( -> PC )
( <- PC )
(Optional — to run without a battery)

You can now use the normal Espruino Web IDE, or a serial terminal application at 9600 baud.

When you connect via Bluetooth, the console will automatically move over. To
stop this, execute to force the console to stay on
.

Note: Serial1 is not enabled by default because it requires the high speed
oscillator to stay on, which increases power draw a huge amount. If you connect
the UART but don’t power down and power on Puck.js, you won’t get a serial port.

Boot Process

To understand how best to save data, it’s best to know how Espruino
loads saved code.

When Espruino starts up, it does a few things:

  • If is pressed or if it reset because of a call to , it sets to .
  • If wasn’t set, it looks for a compressed image ( ) of the interpreter’s state that was saved with . If it exists it unpacks it into RAM.
  • (v2.0 and later) Looks for files named , , and and executes them in sequence. (On Bangle.js these are not executed if is held down, but all other devices execute them each time)
  • Looks for a file named and executes it if it exists (see below)
  • If wasn’t set and wasn’t found in the last step, it looks for a file named and executes it (see below)

  • Initialises any previously-initialised peripherals

  • Runs any handlers registered with
  • Runs a function called if it exists.

If Espruino is reset with it follows the same steps as above, with to .
However in Espruino 2v05 and later, will follow the same steps but will load the
specified file instead of /.

There are two main ways to save code with Espruino:

NATIVE STRINGS ARE GREAT, IF YOU JUST NEED TO READ

A Native String (created with )
is a String that is just a pointer to an area of memory. On most devices there
isn’t enough free RAM for a Native String to point to anything useful, however
if you have data in Flash memory then it can be extremely useful as a way to
access data without taking up any RAM.

While you can use directly, you can also use
to write data to Flash memory using a simple file system. When retrieving data
with
the returned data will be a Native String.

If you save your code with Save on Send then any functions that are
defined will also have their contents stored in a Native String pointing directly
to flash memory.

Time

If you’re logging data at fixed time periods there may be no need to
store the time of each measurement (apart from perhaps the start time). This
will save you memory and will allow you to store more readings in memory.

However sometimes you will want a timestamp (perhaps you want to store
whenever a door opens or closes) — in this case you have no need to store
data, just the time at which an event happened.

You can get the current time in a human readable form with ,
or will give the number of milliseconds since 1970.

The time reported is according to Espruino’s Real-Time Clock. You can set it
with , or can turn on in the
Web IDE’s Communication Settings and the time will be set automatically next time code is
uploaded. (If you’re using the
Web Bluetooth library you can also use on a Web Bluetooth website).

I’ve connected an I2C device, but I get ‘timeout’ errors

This is usually one of four reasons:

  • There are no pull-up resistors. I2C needs resistors between each of its data lines and 3.3v (or 5v) — these are usually in the 4-10 kOhm range. Many modules already have them in, but if you have a module without one then you need to add them before I2C will work.
  • The device’s address is incorrect — sometimes people quote the address as being twice as large as it actually is. If in doubt, try dividing the address by two or multiplying it by two.
  • The device isn’t powered or ground isn’t shared (see the point above)
  • The SDA and SCL wires are mixed up. SDA should be connected to SDA, and SCL to SCL.

Встроенные средства для вычисления HMAC и SHA-1

Генерация пароля устройством занимает более секунды, это не очень комфортно. Библиотека jsSHA реализована на чистом JavaScript, и, хотя время, затрачиваемое на вычисление HMAC SHA-1, практически незаметно на обычном компьютере, на Espruino длительность вычислений становится критичной.

У Espruino есть собственные низкоуровневые нативные реализации вычисления хеш-функций в библиотеках и . Есть и собственная библиотека hmac (хотя она написана на JavaScript, в этом алгоритме сложных вычислений нет и на производительность это не повлияет, в отличие от SHA-1).

Однако использовать напрямую их не получится — в библиотеке haslib нет реализации алгоритма SHA-1, а готовая реализация несовместима с библиотекой hmac. Поэтому для работы со встроенными функциями придется написать «обертку» вокруг функции , совместимый с классом , который используется библиотеками hmac и haslib (исходный код модуля hmac можно посмотреть в каталоге /modules/ непосредственно на сайте espruino.com/, откуда и подгружаются модули функцией require() в Espruino Web IDE). У этого класса всего три метода, причем один из них библиотекой не используется. Еще один момент — объекты типа HASH создаются без ключевого слова new, вызовом конструктора напрямую, поэтому ключевое слово this мы не применяем, создавая новый объект (в переменной self).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

// Класс для вычисления SHA-1 с использованием crypto.SHA1() для использования модулем hmac

constsha1=function(m){

constself={};// Инициализируем результирующий объект

// Сохраняем параметр конструктора в self._message

self._message=m||»;

self.block_size=64;

// Функция `update` просто добавляет новую строку к self._message

self.update=function(m){

self._message+=m;

};

// Вычисление дайджеста от self._message

self.digest=function(){

constdigestArrayBuffer=crypto.SHA1(self._message);

lets=arrBufToStr(digestArrayBuffer);

returns;

};

// Не используется в библиотеке `hashlib`

self.hexdigest=function(){

thrownewError(‘Not implemented’);

};

returnself;

};

Дополнительно понадобится вспомогательная функция, преобразующая объект типа ArrayBuffer в обычную строку, код каждого символа которой равен значению соответствующего байта исходного объекта:

1
2
3
4
5
6
7
8
9
10
11
12

/**
* Преобразование объекта ArrayBuffer в строку
*
* @param {ArrayBuffer} a
* @returns {string}
*/

constarrBufToStr=function(a){

lets=»»;

for(leti=;i<a.length;i++)

s+=String.fromCharCode(ai);

returns;

};

И еще пара функций для конверсии различных представлений данных:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

/**

     * Функция перевода символов строки байтов в их шестнадцатеричное представление
     * в виде строки шестнадцатеричных цифр
     *
     * @param {string} str
     * @returns {string}
     */

conststrToHex=function(str){

lets=»»;

for(leti=;i<str.length;i++)

s+=(256+str.charCodeAt(i)).toString(16).substr(-2);

returns;

};

/**

     * Функция перевода строки шестнадцатеричных цифр в строку байтов
     *
     * @param {string} str
     * @returns {string}
     */

consthexToStr=function(str){

lets=»»;

for(leti=str.length-1;i>;i-=2){

constbyte=str.substr(i-1,2);

s=String.fromCharCode(hexToDec(byte))+s;

}

returns;

};

Теперь готовы все «кирпичики» для того, чтобы написать новый метод вычисления HMAC SHA-1 класса TOTP:

1
2
3
4
5
6
7
8
9

this.hmacSha1_new=function(secretHex,messageHex){

// Преобразуем параметры в нужный вид

constsecretStr=hexToStr(secretHex);

constmessageStr=hexToStr(messageHex);

// Вычисляем HMAC с помощью встроенной функции, передав ей секретный ключ, сообщение

// и наш объект — обертку вокруг `crypto.SHA1`

constshaObj=hmac.create(secretStr,messageStr,sha1);

returnshaObj.hexdigest();// Возвращаем полученное значение HMAC

};

И внутри метода generateHotp() заменим вызов функции this.hmacSha1() на this.hmacSha1_new():

1
2

//const hmacHex = this.hmacSha1(secretHex, counterHex);

consthmacHex=this.hmacSha1_new(secretHex,counterHex);

Длительность вычислений при этом существенно изменится в лучшую сторону, снизившись до 0,17 с, и перестанет вызывать дискомфорт.

Заключение

Espruino — очень дружелюбная и приятная в работе платформа. Хотя в этой статье мы и не попробовали подключить никакой периферии, поддерживается огромное число стандартных внешних модулей с действительно элементарным подключением. Ее можно смело рекомендовать тем, кто знаком с JavaScript и хочет погрузиться в мир микроконтроллеров.

В качестве дальнейшего развития реализации одноразовых паролей можно вместо эмуляции клавиатуры в режиме HID сделать приложение для компьютера, которое будет обмениваться данными с токеном.

Интересным развитием концепции одноразовых паролей стал стандарт FIDO U2F, поддерживаемый Yubico и Google. Авторизация происходит без ввода кода с клавиатуры, достаточно только нажатия на кнопку токена, поддерживающего этот стандарт. При этом токен выступает в роли HID-устройства, с которым браузер взаимодействует напрямую для обмена ключами с сайтом. К сожалению, ресурсов Espruino Pico недостаточно для его поддержки, по крайней мере с использованием реализаций шифрования на JavaScript.

Поддержка HID позволяет использовать такое устройство и в недобрых целях, аналогично USB Rubber Ducky, эмулируя последовательности нажатий клавиш на целевом компьютере и пытаясь, например, создать командный файл для перезагрузки компьютера и добавить его в папку автостарта текущего пользователя.

Оцените статью
Рейтинг автора
5
Материал подготовил
Илья Коршунов
Наш эксперт
Написано статей
134
Добавить комментарий