quarta-feira, 6 de janeiro de 2021

U-BLOX NINA B112 FAZENDO ADVERTISING - ESPRUINO (JAVASCRIPT)

 U-BLOX NINA B112 FAZENDO ADVERTISING - ESPRUINO (JAVASCRIPT)


O objetivo deste BLOG é demonstrar como é possível utilizar a ESPRUINO (JAVASCRIPT) para programar o módulo U-BLOX NINA B112 e transformá-lo em um dispositivo BLE para "data advertising". Foi utilizado o módulo NINA B112 para o teste.

Advertising allows devices to broadcast information defining their intentions.

O exemplo criado no NINA B112 lê a um SWITCH e detecta SHORT, LONG, SHORT SHORT, SHORT LONG, SHORT LONG SHORT, LONG SHORT LONG.

Conforme a sequência, será enviado via advertising os valores 0x80, 0x81, 0x82, 0x83, 0x84 e 0x85.

Também é enviado a tensão da Bateria (VDD) aplicado no NINA B112 e MAC do NINA B112.



Adquirimos então os seguintes componentes



Montado ficou assim



O esquema elétrico é este



Algumas características do Kit

-Botão de RESET;
-Botão de Modo BOOTLOADER (W102);
-Plugável no PROTOBOARD;
-Acesso às várias GPIOS;

Pequena 


Abaixo o roteiro para você seguir:



Espruino é um intérprete de JavaScript para microcontroladores que torna o desenvolvimento de software embarcado rápido e fácil. O intérpretador Espruino é um firmware de código aberto que roda em uma variedade de microcontroladores diferentes.

O Espruino em si não é apenas o firmware ou hardware do interpretador - há também o IDE da Web, ferramentas de linha de comando, documentação, tutoriais e módulos que formam uma solução completa para desenvolvimento de software embarcado..

Muitas LIBRARIES


Compilando 
osboxes@osboxes:~$ mkdir javascript
osboxes@osboxes:~$ cd javascript/
osboxes@osboxes:~/javascript$ git clone https://github.com/espruino/Espruino.git
Cloning into 'Espruino'...
remote: Enumerating objects: 156, done.
remote: Counting objects: 100% (156/156), done.
remote: Compressing objects: 100% (117/117), done.
remote: Total 59581 (delta 76), reused 73 (delta 39), pack-reused 59425
Receiving objects: 100% (59581/59581), 208.91 MiB | 3.43 MiB/s, done.
Resolving deltas: 100% (41614/41614), done.
Updating files: 100% (3087/3087), done.
osboxes@osboxes:~/javascript$ cd Espruino/
osboxes@osboxes:~/javascript/Espruino$ ./scripts/provision.sh NRF52832DK
NRF_SDK15=1
Provision BOARDNAME = NRF52832DK
Provision FAMILY = NRF52
===== NRF52
Installing NRF SDK 15.0 to targetlibs/nrf5x_15/components
mv: cannot move 'nRF5_SDK_15.0.0_a53641a/external' to 'targetlibs/nrf5x_15/external': Directory not empty
mv: cannot move 'nRF5_SDK_15.0.0_a53641a/external/micro-ecc' to 'targetlibs/nrf5x_15/external/micro-ecc': Directory not empty
======================================================
FIXME - SDK15 NFC patches don't apply cleanly
======================================================
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c
Hunk #2 succeeded at 163 (offset 9 lines).
Hunk #3 succeeded at 367 (offset 65 lines).
Hunk #4 succeeded at 401 (offset 65 lines).
Hunk #5 succeeded at 700 (offset 126 lines).
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.h
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c
Hunk #1 succeeded at 738 (offset 126 lines).
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.h
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c
Hunk #1 succeeded at 119 (offset 1 line).
Hunk #2 FAILED at 712.
1 out of 2 hunks FAILED -- saving rejects to file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c.rej
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c
Hunk #1 FAILED at 712.
Hunk #2 FAILED at 728.
2 out of 2 hunks FAILED -- saving rejects to file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c.rej
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c
Hunk #1 FAILED at 709.
1 out of 1 hunk FAILED -- saving rejects to file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c.rej
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c
Hunk #1 succeeded at 729 (offset 126 lines).
Hunk #2 succeeded at 758 (offset 126 lines).
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c
Hunk #1 succeeded at 119 (offset 1 line).
Hunk #2 succeeded at 165 (offset 9 lines).
Hunk #3 succeeded at 733 (offset 126 lines).
Hunk #4 succeeded at 750 (offset 126 lines).
Hunk #5 FAILED at 732.
Hunk #6 FAILED at 753.
Hunk #7 succeeded at 910 (offset 142 lines).
Hunk #8 succeeded at 930 (offset 142 lines).
2 out of 8 hunks FAILED -- saving rejects to file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.c.rej
patching file targetlibs/nrf5x_15/components/nfc/t2t_lib/hal_t2t/hal_nfc_t2t.h
patching file targetlibs/nrf5x_15/modules/nrfx/mdk/nrf.h
patching file targetlibs/nrf5x_15/components/libraries/bootloader/nrf_bootloader.c
patching file targetlibs/nrf5x_15/components/ble/ble_services/ble_nus/ble_nus.c
patching file targetlibs/nrf5x_15/components/ble/ble_services/ble_nus/ble_nus.h
patching file targetlibs/nrf5x_15/components/drivers_nrf/usbd/nrf_drv_usbd_errata.h
===== ARM
arm-none-eabi-gcc installed
osboxes@osboxes:~/javascript/Espruino$ make clean && BOARD=NRF52832DK RELEASE=1 make
Makefile:796: warning: ignoring prerequisites on suffix rule definition
Makefile:800: warning: ignoring prerequisites on suffix rule definition
Cleaning targets
Makefile:796: warning: ignoring prerequisites on suffix rule definition
Makefile:800: warning: ignoring prerequisites on suffix rule definition
Generating platform configs
Generating pin info
Generating JS wrappers
WRAPPERSOURCES = src/jswrap_array.c src/jswrap_arraybuffer.c src/jswrap_dataview.c src/jswrap_date.c src/jswrap_error.c src/jswrap_espruino.c src/jswrap_flash.c src/jswrap_functions.c src/jswrap_interactive.c src/jswrap_io.c src/jswrap_json.c src/jswrap_modules.c src/jswrap_pin.c src/jswrap_number.c src/jswrap_object.c src/jswrap_onewire.c src/jswrap_pipe.c src/jswrap_process.c src/jswrap_promise.c src/jswrap_regexp.c src/jswrap_serial.c src/jswrap_storage.c src/jswrap_spi_i2c.c src/jswrap_stream.c src/jswrap_string.c src/jswrap_waveform.c libs/compression/jswrap_heatshrink.c libs/math/jswrap_math.c libs/graphics/jswrap_graphics.c libs/network/jswrap_net.c libs/network/http/jswrap_http.c libs/network/js/jswrap_jsnetwork.c libs/bluetooth/jswrap_bluetooth.c libs/neopixel/jswrap_neopixel.c
DEFINES = -DGIT_COMMIT=e0a76293 -DNO_ASSERT -DRELEASE -DBUILDNUMBER="119" -DNRF52832DK -DCONFIG_GPIO_AS_PINRESET -DBOARD_PCA10056 -DNRF_USB=1 -DUSB -DNEOPIXEL_SCK_PIN=22 -DNEOPIXEL_LRCK_PIN=23 -DUSE_DEBUGGER -DUSE_TAB_COMPLETE -DUSE_HEATSHRINK -DUSE_MATH -DUSE_GRAPHICS -DUSE_NET -DUSE_NETWORK_JS -DBLUETOOTH -DUSE_NEOPIXEL -DS140 -DNRF_SD_BLE_API_VERSION=6 -D__HEAP_SIZE=0 -DBLE_STACK_SUPPORT_REQD -DSWI_DISABLE0 -DSOFTDEVICE_PRESENT -DFLOAT_ABI_HARD -DNRF52_SERIES -DNRF52832_XXAA -DNRF52832 -DNRF5X -DNRF5X_SDK_15 -DARM -DLINK_TIME_OPTIMISATION -DEMBEDDED
CC libs/compression/heatshrink/heatshrink_encoder.o
CC libs/compression/heatshrink/heatshrink_decoder.o
libs/compression/heatshrink/heatshrink_encoder.c: In function 'heatshrink_encoder_poll':
libs/compression/heatshrink/heatshrink_encoder.c:237:24: warning: this statement may fall through [-Wimplicit-fallthrough=]
  237 |             hse->state = st_flush_bit_buffer(hse, &oi);
      |             ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
libs/compression/heatshrink/heatshrink_encoder.c:238:9: note: here
  238 |         case HSES_DONE:
      |         ^~~~
CC libs/compression/compress_heatshrink.o
CC libs/graphics/bitmap_font_4x6.o
CC libs/graphics/bitmap_font_6x8.o
CC libs/graphics/vector_font.o
.
.
python scripts/check_elf_size.py NRF52832DK espruino_2v08.119_nrf52832.elf
Testing espruino_2v08.119_nrf52832.elf for NRF52832DK
STORAGE: 442368 -> 483328
FS DATA: 415152 -> 415168 (16 bytes)
CODE: 126976 -> 415168 (287708 bytes)
Code area Fits before Storage Area
arm-none-eabi-objcopy -O ihex espruino_2v08.119_nrf52832.elf espruino_2v08.119_nrf52832.hex
Merging SoftDevice
python scripts/hexmerge.py /home/osboxes/javascript/Espruino/targetlibs/nrf5x_12/components/softdevice/s132/hex/s132_nrf52_3.0.0_softdevice.hex espruino_2v08.119_nrf52832.app_hex -o espruino_2v08.119_nrf52832.hex
osboxes@osboxes:~/javascript/Espruino$
COMPATIBILIZANDO COM U-BLOX NINA B112
Altere NRF52832DK.py
import pinutils; info = { 'name' : "nRF52832-MDK", 'link' : [ "https://wiki.makerdiary.com/nrf52832-mdk/" ], # This is the nRF52832-MDK 'default_console' : "EV_SERIAL1", 'default_console_tx' : "D6", 'default_console_rx' : "D5", 'default_console_baudrate' : "9600", 'variables' : 2250, # How many variables are allocated for Espruino to use. RAM will be overflowed if this number is too high and code won't compile. 'bootloader' : 1, 'binary_name' : 'espruino_%v_nrf52832_mdk.hex', 'build' : { 'optimizeflags' : '-Os', 'libraries' : [ 'BLUETOOTH', 'NET', 'GRAPHICS', 'CRYPTO', 'NFC', 'NEOPIXEL' ], 'makefile' : [ 'DEFINES+=-DHAL_NFC_ENGINEERING_BC_FTPAN_WORKAROUND=1', # Looks like proper production nRF52s had this issue 'DEFINES+=-DCONFIG_GPIO_AS_PINRESET', # Allow the reset pin to work 'DEFINES+=-DBLUETOOTH_NAME_PREFIX=\'"nRF52832-MDK"\'', 'DFU_PRIVATE_KEY=targets/nrf5x_dfu/dfu_private_key.pem', 'DFU_SETTINGS=--application-version 0xff --hw-version 52 --sd-req 0x8C' ] } }; chip = { 'part' : "NRF52832", 'family' : "NRF52", 'package' : "QFN48", 'ram' : 64, 'flash' : 512, 'speed' : 64, 'usart' : 1, 'spi' : 3, 'i2c' : 2, 'adc' : 1, 'dac' : 0, 'saved_code' : { 'address' : ((118 - 10) * 4096), # Bootloader takes pages 120-127, FS takes 118-119 'page_size' : 4096, 'pages' : 10, 'flash_available' : 512 - ((31 + 8 + 2 + 10)*4) # Softdevice uses 31 pages of flash, bootloader 8, FS 2, code 10. Each page is 4 kb. }, }; devices = { 'BTN1' : { 'pin' : 'D16', 'pinstate' : 'IN_PULLDOWN' }, # Pin negated in software 'BTN2' : { 'pin' : 'D30', 'pinstate' : 'IN_PULLDOWN' }, # Pin negated in software 'LED1' : { 'pin' : 'D8' }, # Pin negated in software 'LED2' : { 'pin' : 'D16' }, # Pin negated in software 'LED3' : { 'pin' : 'D18' }, # Pin negated in software 'RX_PIN_NUMBER' : { 'pin' : 'D5'}, 'TX_PIN_NUMBER' : { 'pin' : 'D6'}, 'CTS_PIN_NUMBER' : { 'pin' : 'D7'}, 'RTS_PIN_NUMBER' : { 'pin' : 'D5'} # Pin D22 is used for clock when driving neopixels - as not specifying a pin seems to break things }; # left-right, or top-bottom order board = { 'left' : [ 'VDD', 'VDD', 'RESET', 'VDD','5V','GND','GND','','','D3','D4','D28','D29','D30','D31'], 'right' : [ 'D27', 'D26', 'D2', 'GND', 'D25','D24','D23', 'D22','D20','D19','', 'D18','D17','D16','D15','D14','D13','D12','D11','', 'D10','D9','D8','D7','D6','D5','D21','D1','D0'], '_notes' : { 'D6' : "Serial console RX", 'D8' : "Serial console TX" } }; board["_css"] = """ """; def get_pins(): pins = pinutils.generate_pins(0,31) # 32 General Purpose I/O Pins. pinutils.findpin(pins, "PD0", True)["functions"]["XL1"]=0; #OK NC pinutils.findpin(pins, "PD1", True)["functions"]["XL2"]=0; #OK NC pinutils.findpin(pins, "PD2", True)["functions"]["I2C_SDA"]=0; #OK AN1 i2c_sda pinutils.findpin(pins, "PD3", True)["functions"]["I2C_SCL"]=0; #OK AN0 i2c_scl pinutils.findpin(pins, "PD4", True)["functions"]["ADC1_IN2"]=0; #OK AN2 pinutils.findpin(pins, "PD5", True)["functions"]["RXD"]=0; #OK TXD D0 pinutils.findpin(pins, "PD6", True)["functions"]["TXD"]=0; #OK TXD D1 pinutils.findpin(pins, "PD7", True)["functions"]["CTS"]=0; #OK CTS D2 pinutils.findpin(pins, "PD8", True)["functions"]["LED_1"]=0; #OK LED1 D9 pinutils.findpin(pins, "PD9", True)["functions"]["NFC1"]=0; #OK NFC1 D6 pinutils.findpin(pins, "PD10", True)["functions"]["NFC2"]=0; #OK NFC1 D7 pinutils.findpin(pins, "PD11", True)["functions"]["SPI_CS"]=0; #OK SPI_CS D10 pinutils.findpin(pins, "PD12", True)["functions"]["SPI_MISO"]=0; #OK SPI_MISO D12 pinutils.findpin(pins, "PD13", True)["functions"]["SPI_MOSI"]=0; #OK SPI_MOSI D11 pinutils.findpin(pins, "PD14", True)["functions"]["SPI_SCK"]=0; #OK SPI_SCK D13 pinutils.findpin(pins, "PD16", True)["functions"]["LED_2"]=0; #OK LED2/SWITCH1 pinutils.findpin(pins, "PD18", True)["functions"]["LED_3"]=0; #OK LED3 D4 pinutils.findpin(pins, "PD28", True)["functions"]["ADC1_IN5"]=0; #OK AN5 pinutils.findpin(pins, "PD29", True)["functions"]["ADC1_IN4"]=0; #OK AN4 pinutils.findpin(pins, "PD30", True)["functions"]["ADC1_IN3"]=0; #OK AN3/SWITCH2 pinutils.findpin(pins, "PD31", True)["functions"]["RTS"]=0; #OK RTS D3 # everything is non-5v tolerant for pin in pins: pin["functions"]["3.3"]=0; #The boot/reset button will function as a reset button in normal operation. Pin reset on PD21 needs to be enabled on the nRF52832 device for this to work.
  return pins 

Grave o código HEX usando o utility J-FLASH LITE ou NRFGO STUDIO no NINA B112 (EVK-NINA-B1)

espruino_2v07.30_nrf52832_mdk.hex






Resete o NINA B112

Instale o ESPRUINO IDE (Native)

Instale o USB DONGLE CSR 4.0 (drivers)


Mas atenção!

Para o Windows 8.1 e posterior
O IDE é capaz de usar os drivers BLE do próprio Windows. A única configuração necessária é que você vá para as configurações de Bluetooth do seu sistema e clique em Conectar (Parear no Windows 10) no seu dispositivo NINA B112. Isso expõe ao sistema e garante que ele apareça no IDE da Web. Para o Windows anterior ao 8.1
Como as versões do Windows anteriores à 8.1 não suportam Web Bluetooth no sistema operacional, o noble (que o Espruino IDE usa) precisa acessar diretamente o adaptador BLE - portanto, é necessário garantir que o driver WinUSB seja carregado para ele (como oposição a um driver específico do fabricante). Baixe o Zadig e execute-o - é apenas um executável Vá para Opções -> Listar todos os dispositivos Escolha o seu adaptador BLE (o meu é CSR8510 A10) Certifique-se de que o WinUSB esteja definido como o driver Agora, quando você executar o IDE da Web nativo e clicar em "conectar" no canto superior esquerdo, deverá ver uma lista de dispositivos BLE conectáveis.





Execute o ESPRUINO IDE (Native)



Faça o SCAN para encontrar o NINA B112




Conecte ao NINA B112





Transfira o SCRIPT JAVASCRIPT abaixo 



var k = 0; var SWBtn = require("https://raw.githubusercontent.com/muet/EspruinoDocs/master/modules/SWButton.js"); //Just to DEBUG var on = false; function LedBlynk() { setInterval(function() { //inverte estado da variável ON on = !on; //escreve no LED D12.write(on); }, 1000); } function hexToBytes(hex) { for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return bytes; } function UpdateAdv() { var ii = Math.floor(NRF.getBattery()); var ff = NRF.getBattery()-Math.floor(NRF.getBattery()); ff = ff * 100; var mac = NRF.getAddress(); var newstr = mac.replace(":", ""); newstr = newstr.replace(":", ""); newstr = newstr.replace(":", ""); newstr = newstr.replace(":", ""); newstr = newstr.replace(":", ""); var vec = hexToBytes(newstr); NRF.setAdvertising({},{manufacturer: 0x0590, manufacturerData:[ii,ff,kk,vec]}); } //Capture the Key Events function ClickCapture() { pinMode(D11, 'input_pulldown'); var mySWBtn = new SWBtn(function(k){ //console.log("Button detected " + k); // log key press pattern if (k === "S" ) { kk = 0x80; UpdateAdv(); } else if (k === "L" ) { kk = 0x81; UpdateAdv(); } else if (k === "SS" ) { kk = 0x82; UpdateAdv(); } else if (k === "SL" ) { kk = 0x83; UpdateAdv(); } else if (k === "SLS") { kk = 0x84; UpdateAdv(); } else if (k === "LSL") { kk = 0x85; UpdateAdv(); } },D11); } //First Function to execute during the BOOT function onInit() { //LedBlynk(); ClickCapture(); }
















Execução

No Pino GPIO 2 do módulo foi colocado um SWITCH, o qual aterrará o pino quando pressionado.
Ao pressionar o SWITCH, é monitorado se é SHORT, LONG, SHORT SHORT, SHORT LONG, SHORT LONG SHORT, LONG SHORT LONG

Conforme a sequência, será enviado via advertising os valores 0x80, 0x81, 0x82, 0x83, 0x84 e 0x85.


Ao executar o programa no NINA B112, execute um o APP com BLE SCAN




Neste caso, 023F é a tensao da Bateria, 80 significa SHORT click e D38C...é o MAC.

Para executar depois do BOOT

reset();save();

 

Sobre a SMARTCORE

A SmartCore fornece módulos para comunicação wireless, biometria, conectividade, rastreamento e automação.
Nosso portfólio inclui modem 2G/3G/4G/NB-IoT/Cat.M, satelital, módulos WiFi, Bluetooth, GNSS / GPS, Sigfox, LoRa, leitor de cartão, leitor QR code, mecanismo de impressão, mini-board PC, antena, pigtail, LCD, bateria, repetidor GPS e sensores.
Mais detalhes em www.smartcore.com.br

Nenhum comentário:

Postar um comentário