Настройка espruino web ide
If you haven't already, see the getting started guides for:
for information on how to get the Web IDE connected to your device.
Режим HID, эмуляция клавиатуры
Espruino поддерживает работу через USB в режиме HID (Human Interface Device), что позволяет эмулировать клавиатуру, мышь или планшет (подробнее — здесь).
Для эмуляции USB-клавиатуры необходимо подключить внешний модуль USBKeyboard . Введем в правой части окна в текстовом редакторе:
Installing
Тестирование подключения
Проверим корректное соединения с платформой.
Программная перезагрузка
В чёрном окне консоли наберите команду:
Плата перезагрузится, а в консоли отобразиться баннер платы.
Обратите внимание на версию интерпретатора JS (2v01.49) в примере. Если плата работает не корректно, обновите прошивку платформы до самой свежей.
Locally hosted version
If you have a Raspberry Pi, you can install the EspruinoHub software on it, which will allow you to program any Bluetooth LE Espruino devices within range of the Pi straight from a Web Browser on any network-connected computer.
Соединение с платой
Espruino Web IDE поддерживает два типа соединения:
Development version
We only update the Web IDE when we're sure that everything is working. If you want the 'Cutting Edge' version then you can get it directly from GitHub. There are detailed instructions on how to get started on that page.
This page is auto-generated from GitHub. If you see any mistakes or have suggestions, please let us know.
Несмотря на огромное количество устройств на базе микроконтроллеров, созданных на волне успеха Arduino, считаные единицы из них имеют форм-фактор обычной флешки, подходящий для непосредственного включения в разъем USB компьютера (USB Type-A). Один из наиболее любопытных их представителей — Espruino Pico.
Вообще говоря, Espruino — это несколько вариантов микроконтроллерных устройств, в которых прошит встроенный интерпретатор JavaScript. Espruino Pico — самое миниатюрное из них. Оригинальный интерпретатор JavaScript, используемый в Espruino, предназначен для быстрой разработки на устройствах с ограниченными процессорными ресурсами. Есть его версии для целого перечня платформ, начиная с ESP8266 и до Raspberry Pi.
Для Espruino существует большое число готовых подгружаемых модулей для самого разнообразного периферийного оборудования, совместимого с экосистемой Arduino (см. раздел модули на сайте Espruino) и инструкций по его подключению (в разделе инструкций и примеров). Есть официальный форум.
Online
The easiest way to use the Web IDE is straight from the Web Browser
You'll need an up to date version of Chrome, Edge or Opera to get access to Web Bluetooth and Web Serial options.
Note:
- Versions of Windows before Windows 10 don't support Web Bluetooth. You'll need to install the Native application (below).
- Web Bluetooth and Web Serial may not be enabled in your Browser by default. Have a look at the Quick Start guide for information on how to enable it.
Видеобзор
Установка и настройка
Продолжение доступно только участникам
Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», позволит скачивать выпуски в PDF, отключит рекламу на сайте и увеличит личную накопительную скидку! Подробнее
Вариант 2. Открой один материал
Отработка нажатий на встроенную кнопку
Прочитать состояние кнопки позволяет функция digitalRead() :
Мониторить состояние кнопки можно, периодически считывая ее состояние с помощью setInterval() , однако более корректным будет использование функции watch() :
Online
The easiest way to use the Web IDE is straight from the Web Browser
You'll need an up to date version of Chrome, Edge or Opera to get access to Web Bluetooth and Web Serial options.
Note:
- Versions of Windows before Windows 10 don't support Web Bluetooth. You'll need to install the Native application (below).
- Web Bluetooth and Web Serial may not be enabled in your Browser by default. Have a look at the Quick Start guide for information on how to enable it.
Быстрый старт
Для Windows тебе, скорее всего, понадобится установить драйвер виртуального COM-порта.
На Mac никаких дополнительных манипуляций потребоваться не должно. Устанавливаем среду Espruino Web IDE из Chrome Web Store.
Рабочая область Espruino Web IDE разделена на две части. В левой расположено окно консоли, в правой — редактор. Нажав на символ >, редактор можно переключить в графический режим, основанный на среде Blockly, аналогичной Scratch, что может подойти начинающим.
Для подключения к плате необходимо нажать на желтую иконку с разъемом в верхнем левом углу окна. Будет выведен запрос на выбор порта.
При успешном подключении будет выведено приглашение консоли Espruino:
Проверим работоспособность вводом 1+2 :
Development version
We only update the Web IDE when we're sure that everything is working. If you want the 'Cutting Edge' version then you can get it directly from GitHub. There are detailed instructions on how to get started on that page.
This page is auto-generated from GitHub. If you see any mistakes or have suggestions, please let us know.
The Web IDE is the preferred way to program Espruino. It's got a syntax-highlighted editor as well as support for dynamically loading modules and for upgrading Espruino's Firmware. You might want to check out other ways of programming Espruino devices.
Что-то пошло не так?
Обновление прошивки
Если доступно обновление прошивки, в правом верхнем углу появится соответствующая иконка. При нажатии на эту иконку запустится мастер обновления, который пошагово проинструктирует, что нужно сделать для обновления прошивки.
Консольные команды
Через консоль можно работать с подключённой платой «налету»: исполнять выражения, вызывать функции, просматривать значения переменных и т.д. Попробуйте, например, ввести в консоль 6 + 8 и нажать Enter. Плата выполнит команду и вернёт результат 14 .
Шаг 3. Установка драйвера
Если у вас Windows, установите драйвер для USB-интерфейса микроконтроллера STM32. Для Mac OS и Linux драйвер не нужен.
Беспроводное подключение
Поддерживаемые устройства
Беспроводное подключение к среде Espruino Web IDE доступно только при наличии беспроводных приёмопередатчиков на обоих устройствах: Espruino и ПК.
На ПК должен быть включён модуль Bluetooth. Если он физически отсутствует, его можно приобрести отдельно.
Инструкция по подключению
В среде Espruino Web IDE в верхнем левом углу нажмите кнопку .
Выбирайте подключение через Web Bluetooth.
Откроется окно поиска новых устройств.
Выберите интересующее вас устройство и нажмите на кнопку «Подключить».
После успешного подключения, вы увидите в консоли надпись «Connected». Фон кнопки изменит цвет на зелёный и в нижнем правом углу всплывёт окошко с уведомлением, что плата успешно подключена к компьютеру.
How does the Espruino IDE work?
Once connected in the IDE, writing on the left-hand side will communicate directly with the device and executes commands immediately.
The right-hand side is a text editor. You can click the >icon to swap to a graphical code editor, and can click to send the code you wrote on the right-hand side to Espruino.
On new versions of the IDE you'll see some text and a down-arrow below the upload icon (the Upload Icon) - this allows you to quickly choose where you save your code - see the page on Saving for more information.
If you're using any version of the Espruino IDE, you can click on in the top right, then:
- Tour for a quick tour of the various parts of the Espruino IDE
- Tutorial for a step by step guide to writing your first code on Espruino
Загрузка программы c использованием библиотек Амперки
Проверим плату на первом эксперименте из набора Йодо.
В примере используется пин P1 который установлен на платформе Iskra JS. Если вы используете другую платформу с интерпретатором JavaScript, имена объектов и пинов могут отличатся.
Поздравляем, вы полностью настроили железо со средой Espruino IDE. Можете смело переходить к изучению всех возможностей программирования микроконтроллеров на JavaScript.
The Web IDE is the preferred way to program Espruino. It's got a syntax-highlighted editor as well as support for dynamically loading modules and for upgrading Espruino's Firmware. You might want to check out other ways of programming Espruino devices.
As a Native application
The Web IDE is available as:
Older versions of the IDE (not recommended) are available here
For Windows 8.1 and later
The Native IDE is able to use Windows' own BLE drivers. The only configuration needed is for you to go to your system's Bluetooth settings and to click Connect ( Pair on Windows 10) on your Puck.js device. This exposes it to the system and makes sure it shows up in the Web IDE.
For Windows earlier than 8.1
Since Windows versions earlier than 8.1 don't support Web Bluetooth in the OS, noble (which the Espruino IDE uses) has to be able to access the BLE adaptor directly - so you have to make sure the WinUSB driver is loaded for it (as opposed to a manufacturer-specific driver).
- Download Zadig and run it - it's just an executable
- Go to Options -> List all Devices
- Choose your BLE adaptor (mine is CSR8510 A10 )
- Make sure WinUSB is set as the driver
- Now when you next run the Native Web IDE and click 'connect' in the top left, you should see a list of connectable BLE devices.
Native applications for other platforms
If you require a native version of the IDE for other platforms, you can install the Development version from GitHub (below):
WARNING
Все примеры кода предназначены исключительно для образовательных целей. Данное решение обладает пониженным уровнем безопасности, секретный ключ хранится на устройстве в открытом виде. Не используй этот код в критически важных системах. Применяй для авторизации промышленно выпускаемые устройства.
Характеристики Espruino Pico
- Espruino Pico — самая миниатюрная из плат Espruino, ее размеры 3,3 × 1,5 см.
- На контакты платы выведено 22 порта ввода-вывода общего назначения, в том числе девять аналоговых входов, 21 с поддержкой ШИМ (PWM), два последовательных порта, три порта SPI, три порта I2C; все GPIO могут работать с 5 В (что важно для совместимости с модулями, разработанными для Arduino).
- Встроенный разъем USB Type-A позволяет включать устройство непосредственно в USB-порт компьютера без дополнительных кабелей аналогично обычной флешке.
- Два встроенных светодиода и одна кнопка позволяют реализовать минимальное управление устройством без внешних компонентов.
- 32-битный процессор ARM Cortex M4 84 МГц — STM32F401CDU6.
- 384 Кбайт флеш-памяти, 96 Кбайт ОЗУ.
- Встроенный регулятор напряжения 3,3 В 250 мА, работающий в диапазоне от 3,5 до 16 В, позволяет подключать внешний аккумулятор без дополнительных компонентов.
- Потребляемый ток в режиме сна: < 0,05 мА — более двух с половиной лет от батареи 2500 мА ∙ ч.
- Встроенный полевой транзистор для управления цепями с высоким рабочим током.
Александр Лыкошин
Директор продуктового направления компании «Телигент». Член ACM, IEEE, IEEE Communications Society, IEEE Computer Society. Преподает в МЭСИ на кафедре АСОИУ Института компьютерных технологий.
Start writing code!
Now you can type commands and they will be executed (you can also copy and paste them in to the terminal window).
Try typing the following in the left-hand side of the Web IDE, and press 'Enter' after it:
This should return =3 . If it doesn't, there might have been some text entered already by the terminal application. Press Ctrl-C to clear this, and try again.
Every time you type a command and press enter, it will be executed immediately. = will be displayed followed by the result. If there is no result (for instance if you were executing a function that returned no value), =undefined is displayed.
Remember to enter capital letters where they appear above - JavaScript (and so Espruino) is case-sensitive, so for instance digitalwrite won't work while digitalWrite will.
Is Uncaught ReferenceError: "LED1" is not defined displayed? If so you're probably not using an offical board (which all have LED1 defined) - you can always attach an LED to a pin and type var LED1 = you_pin_name to continue.
If all goes well, =undefined will be displayed, however the LED1 light on the board will light up. This allows you to set voltages that come out of the processor ( 1 =3.3 volts, 0 =0 volts). Instead of LED1 , you can use any pin name, such as A1 or B5 (there's a handy diagram of your device's pins under the Pinout heading in your device's reference page).
Now, press the 'up' arrow. This will display the last command you ran, and will show the text digitalWrite(LED1,1) again. Press the left arrow until the cursor moves to the end of 1 , press backspace, then press 0 . It should now look like this:
You can now step back to the end of the line (using the right arrow, or the 'end' key) and can press enter to execute the command (which will turn the LED off). If you press enter before the cursor is on the end of the line, it won't execute the command, but will split it on to two lines (you can press backspace again to back up).
For the next bit, we need to create a variable. Type:
Then press enter - this will create a new variable called on and will set its value to the boolean false .
You can now write a function. Type the following:
When you hit 'enter' after the first line, the command wasn't executed, but instead Espruino just created a new line because there was an unclosed open bracket. If you don't define functions with an open bracket on the end of the line then they will be executed immediately, which is probably not what you want (if you really want to put your brackets on a new line, press Alt-Enter at the end of the line function toggle() - but we don't recommend this).
What if you created a new line by mistake? Just hit backspace. Or if you're totally confused and just want to start again, press Ctrl-C and the text you typed will be deleted.
Once you've hit enter after the last line, the text =function () < . >will be displayed in the terminal window. This means that your function (called toggle ) is defined. So what does it do? The on variable stores a value which is either true or false . The command on = !on; makes the value of on true if it was false before, or false if it was true before. If you pronounce = as 'becomes', and ! as 'not', reading the line makes more sense ( on becomes not on ).
The next line takes the changed value of on (either true of false ) and applies it to the digital output (in this case LED number 1). Every time you use the toggle function, the value of on toggles between true and false, and so turns the LED on or off.
Now we can try it, type the following and hit enter:
If you want to run it again, just hit the up arrow (to find the command in history) followed by enter. Every time you run it, the LED will change state from on to off or vice versa.
This will call the toggle function every 500ms (eg. twice a second), so the LED will start blinking. The new variable called i (which was defined by var ) is a reference to the timer we have created - this will be useful later!
But what if we want to change the toggle function? First let's see if what we want to to makes sense.
If Uncaught ReferenceError: "LED2" is not defined is displayed then your device only has one LED. You'll have to skip using LED2 in the next steps.
You can also get a similar effect by hitting the up arrow until you get back to the command where you defined toggle . Now the function is displayed, press the left arrow to move the cursor backwards, and start to edit the function. Add a new line at the end so that it looks like this (to add a line after digitalWrite , move the cursor to the end of the line, and press 'enter'):
Now, move the cursor right to the end of the last line using the arrow keys (or press 'page down'), and press enter. This will execute the command, which will redefine the function - and now LED1 will light, then LED2, then LED1 - and so on.
You can now change the speed the lights flash, using this command:
This is the same as if you originally called setInterval( . , 200) - toggle is now called every 200ms (5 times a second)
And if you want your lights to stop flashing - just type this:
Note that just typing clearInterval() without any arguments will clear all active intervals.
If you want to start completely from scratch and wipe out everything you have done, just type:
If you press the reset button on the board (if your board has one), Espruino will also reset. However we don't recommend this - on most boards this will reset the USB/Bluetooth connection as well, so you may need to restart your terminal application, or in some cases even unplug and re-plug the device.
If you power off or reset Espruino using the reset button, it will lose all the code that you wrote. You can save the state of Espruino so this doesn't happen using the save() command (more information).
The save() command saves the current state of the pins and on-chip peripherals, as well as all your functions, variables, watches and timers. The commands that you typed in previously won't be executed again though. If you want to execute some code when Espruino starts (for example you may need to initialise some external bit of hardware like an LCD), you can use the init event on E . For example this bit of code lights the red, then green LEDs each time Espruino starts up:
Note: This code won't work on Bangle.js. Since it has no LEDs it uses a special 'virtual' pin for LEDs, which is not compatible with being passed to digitalWrite in an array. Instead, you can just do: digitalWrite(LED1. );digitalWrite(LED2. );
Note: You can add a second handler to do something else when Espruino starts up, just by calling E.on('init', . ) again. If you write a function called onInit , that will automatically be executed as well.
The code above uses a few extra features in Espruino that weren't covered above:
- You can pass an array of pins into digitalWrite (the same applies to digitalRead ). If you do that, the value you supply will be treated as a binary value, with the least significant bit going to the rightmost pin in the array and so on.
- If you pass a string into setTimeout or setInterval , it'll be treated in the same way as a function and will be executed after a certain time period.
If you do manage to save something to Espruino that causes it not to work, don't worry - you can easily recover it. Just see the Troubleshooting page.
Now you've got an idea how to use Espruino:
- Have a look at your board's reference page - it contains more in-depth information about your board, as well as for links to tutorials that specifically use your board:
- Espruino Pico
- Espruino WiFi Espruino
- Other board? It may be listed in the Reference
This page is auto-generated from GitHub. If you see any mistakes or have suggestions, please let us know.
Espruino Web IDE — это приложение для написания программы и загрузки её в плату. Утилита также содержит в себе консоль для наблюдения и отладки вывода консольных команд.
Интерфейс среды
Окно среды состоит из двух основных частей: слева — окно консоли, справа — окно исходного кода.
Типовой сценарий работы:
загружаете его в плату кнопкой ;
From the Chrome Web Store
You can install the IDE from the Chrome Web Store
This video is from the Quick Start page, which contains extra information on installing the Web IDE:
Note:
- Google has deprecated the Chrome Web Store and will be removing it during 2021, so this installation method may not be available soon.
- On Windows, the Web IDE from the Chrome Web Store doesn't support Bluetooth Low Energy, needed for communicating with Bluetooth LE Espruino device. If you're using Windows you'll need to use the Native Application (below).
История Espruino
Платформа Espruino — не самый молодой проект. Первые публичные упоминания о ней датируются еще 2012-м, и в 2013-м была проведена успешная кампания на Kickstarter по сбору средств на развитие проекта. Ее успех позволил в конце 2014 года провести следующую кампанию, на проект более компактной версии под названием Espruino Pico в форм-факторе размером в половину обычной флешки.
Загрузка первой программы
Среда настроена, плата подключена. Прошейте управляющую плату, программой приведённой ниже. Светодиод «LED1» на плате будет загораться и гаснуть каждые 500 миллисекунд.
Немного модифицируем код, чтобы изменить частоту мигания светодиода.
Замените значение 500 на 100 и перепрошейте плату.
Теперь светодиод «LED1» будет загораться и гаснуть каждые 100 миллисекунд — в 5 раз быстрее исходной версии.
В примере используется объект LED1 который установлен на платформе Iskra JS. Если вы используете другую платформу с интерпретатором JavaScript, имена объектов и пинов могут отличатся.
As a Native application
The Web IDE is available as:
Older versions of the IDE (not recommended) are available here
For Windows 8.1 and later
The Native IDE is able to use Windows' own BLE drivers. The only configuration needed is for you to go to your system's Bluetooth settings and to click Connect ( Pair on Windows 10) on your Puck.js device. This exposes it to the system and makes sure it shows up in the Web IDE.
For Windows earlier than 8.1
Since Windows versions earlier than 8.1 don't support Web Bluetooth in the OS, noble (which the Espruino IDE uses) has to be able to access the BLE adaptor directly - so you have to make sure the WinUSB driver is loaded for it (as opposed to a manufacturer-specific driver).
- Download Zadig and run it - it's just an executable
- Go to Options -> List all Devices
- Choose your BLE adaptor (mine is CSR8510 A10 )
- Make sure WinUSB is set as the driver
- Now when you next run the Native Web IDE and click 'connect' in the top left, you should see a list of connectable BLE devices.
Native applications for other platforms
If you require a native version of the IDE for other platforms, you can install the Development version from GitHub (below):
From the Chrome Web Store
You can install the IDE from the Chrome Web Store
This video is from the Quick Start page, which contains extra information on installing the Web IDE:
Note:
- Google has deprecated the Chrome Web Store and will be removing it during 2021, so this installation method may not be available soon.
- On Windows, the Web IDE from the Chrome Web Store doesn't support Bluetooth Low Energy, needed for communicating with Bluetooth LE Espruino device. If you're using Windows you'll need to use the Native Application (below).
Загрузка первой программы в Espruino — управление встроенными светодиодами
Следующий шаг стандартный — «помигать светодиодом». Для этого в правой части среды разработки уже есть готовый код:
Единственное, что можно прокомментировать в этих строках, — это использование встроенного объекта LED1 , представляющего собой экземпляр специального класса Pin , который предназначен для управления портами ввода-вывода. В данном случае метод write используется для задания уровня на выходе порта (логические ноль/единица), к которому подключен красный светодиод, установленный на плате.
Нажмем на иконку «Send to Espruino».
Через мгновение в консоль будет выведен лого и замигает красный светодиод:
Для отключения функции setInterval() можно ввести в консоли clearInterval() .
LED , LED1 и B2 (номер контакта микроконтроллера, к которому подключен светодиод) соответствуют красному светодиоду, LED2 и B12 (он подключен к контакту B12 ) — зеленому. Адресовать светодиоды можно и с помощью номеров контактов, к которым они подключены: B2 эквивалентно LED и LED1 , B12 — LED2 .
Можно воспользоваться и хорошо знакомой ардуинщикам функцией digitalWrite() :
Есть возможность изменить состояние на заданный период функцией digitalPulse() :
Или задать целую последовательность:
Порты, к которым подключены светодиоды, смонтированные на плате, не поддерживают режим широтно-импульсной модуляции (ШИМ), или Pulse-Width Modulation (PWM), и попытка изменить их яркость, записав что-то в эти порты функцией analogWrite() , приведет к ошибке. Но управление яркостью светодиодов все-таки возможно с помощью встроенного режима программной эмуляции ШИМ:
Более того, можно одновременно с этим задать периодическое включение и отключение:
Проводное подключение
В среде Espruino Web IDE в верхнем левом углу нажмите кнопку .
Найдите среди них свою плату простым перебором.
После успешного подключения, вы увидите в консоли надпись «Connected». Фон кнопки изменит цвет на зелёный и в нижнем правом углу всплывёт окошко с уведомлением, что плата успешно подключена к компьютеру.
Installing
Locally hosted version
If you have a Raspberry Pi, you can install the EspruinoHub software on it, which will allow you to program any Bluetooth LE Espruino devices within range of the Pi straight from a Web Browser on any network-connected computer.
Шаг 2. Добавление настроек Амперки
Добавьте в Espruino IDE поддержку платы Iskra JS и библиотек от Амперки в автоматическом или ручном режиме.
Автоматический режим
Если у вас версия от Google Chrome, просто кликните по текущей ссылке. Во всех остальных случаях настройки придётся вбить вручную.
Ручной режим
Шаг 1. Установка среды
Среда программирования Espruino Web IDE поддерживает три типа инсталляции:
Если у вас операционная система Windows 7 или 8, то Espruino из магазина приложений Chrome и web-версия могут не видеть COM-порты. Используйте нативное приложение в этом случае.
Online приложение
Для старта, просто откройте Web-версию Espruino IDE.
Приложение из магазина Google Chrome
Приложение для рабочего стола
Скачайте и установите самую последнюю десктопную версию версию Espruino Web IDE. Espruino.exe находится почти в самом конце списка.
Читайте также: