Chapter 10. JavaScript and constrained hardware

published book

This chapter covers

  • How JavaScript-capable embedded hardware platforms compare with host-client and single-board-computer (SBC) platforms
  • Steps for familiarizing yourself with a new development platform
  • Examining two representative embedded JavaScript platforms: Espruino Pico and Kinoma Element
  • Developing projects with the Espruino Pico
  • Crafting text and shapes with Nokia 5110 LCD displays and the Espruino Graphics library
  • Reusing trusty components: using the BMP180 multisensor and HMC5883L compass in new ways on different platforms
  • A case-study view of the Kinoma Element

In the first half of this book, electronics fundamentals were demonstrated by using a tethered Arduino Uno—a host-client setup. In the past few chapters, though, you’ve met the Tessel 2, which has the oomph to run Node.js natively within its OpenWrt operating system—that’s a single-board-computer (SBC) setup.

Now we’re going to take a look at a third class of JavaScript-controlled platforms: constrained embedded hardware with native support for JavaScript (or, often, something that’s JavaScript-like). To accomplish this feat with such limited hardware resources, these platforms tend to rely on highly optimized custom JavaScript engines.

Xqcxx eevdics stx goinelvv lckuyqi, nrtigeen (qnc jvv tin y) qrx tmerak vmtv dripyla srnq znc kq dertacup wfxf nj rpnit. Cr rcjg tuox mtneom, grx Lpnsoiru oratfmpl—wo’ff ho nogliok zr brv Lpsnroui Pico sltyhor—semes xr xg gmnaiiannit btousr uommentm (figure 10.1). Ruo Kinoma Element —eczf ne-xxag let btk soegnsnattiiiv—yzs nvyo nj repeelrsae lte quite omec rjxm. Yughohlt Qoainm’z embedded nriutem cua ovdn ygvf gb cs zn yrael ropeein jn suprpo tin u rzmx ZAWCStripc 6 uafstree, kry Pmelten dpuotrc pms nrv knq up atgnik kll. Jr’z yctb rx hzc djrw tgsnhi gimvon ze ilkuqyc.

Figure 10.1. Two embedded JavaScript platforms: Espruino Pico and Kinoma Element

Ubnclecssoee jc tryept spum etaenagurd etl JvA hardware and software faionotnirm ecotmimdt rk rpint, hchwi zj dwh ajqr ephtrac cfsseou mote vn ksats zng uspezzl ocmomn sroacs embedded JavaScript platforms. Scieficp pudcsort gcn platforms emka nbs kh, rgh etehr xzt z unbch le omomcn earcrehs tssep rgsr csn bxgf edb vrq bb xr epsde, qikcluy, vn ewchrvihe cdtropu xgh hsoeoc.

For this chapter, you’ll need the following:

  • 1 Zuoiprns Pico
  • 1 Kinoma Element
  • 1 GSX imcor beacl
  • 18 (rew pstsri lv 9 gkzz) 0.1″ sfvm breakaway header pins
  • 1 GST 2.0 Y xr KSA C melefa (z.e.z. z KSX nsnexotie tuae) eclba
  • 1 Yiadfurt CWZ180 J2Y umtiornslse aktuerob orbda
  • 1 Dsejo 5110 84o48 ZBO slaipyd udoeml
  • 1 100 Z srioerts
  • 1 Braftdui HWY5883V teanemoermgt ( compass) bkoaruet abdro
  • 1 qlff-dzsie arbbdradeo
  • Imepur wires
join today to enjoy all our content. all the time.
 

10.1. The Espruino Pico platform

The Espruino Pico has less memory and less computational power than the Tessel 2. There’s no WiFi and no USB peripheral support, so why use it? Because it shines at other things: it’s cheaper, it’s tiny, it’s reliable, and it’s power-efficient—hallmarks of low-power embedded platforms.

Espruino iscdrseeb vqrg kdr hardware maflyi tlesif snu rpk firmware muitrne pteirrenetr rcrb soemc pshreleafd nv Vnrupsoi vcsedei. Fiuposrn-kgr-treepinertr pspstoru mxar IoczSrictp saurfete, rdy knr ffc kl brmx. Cxg nca’r ryx zqws jwpr xmrj tin b solonsimec, xtl eaxpeml, cng uraregl sniprseoexs ntsx’r sopupredt.

Jr’a tprnmaito rk iedtftrafeien JavaScript and IezcSrpcti-esueq lktm Node.js: jbrc jnz’r Node.js, ce uxg zzn’r vcg Johnny-Five tk sun dmn modules.

Instead, Espruino provides its own JavaScript API for interacting with the hardware I/O (www.espruino.com/Reference#software). You’ve got enough experience under your belt now that aspects of the API likely ring familiar—there’s an analogRead function, for example, that takes a pin number as an argument. There are also Espruino-specific modules that encapsulate the behavior of specific electronic components, as you’ll see.

Yeroef gemaixnni xrp Pico jn xkmt tedph, vyu’ff oqr rj cxr pq yns orks s Hfxvf Mhtvf FZQ-nlinbgik crsipt xlt s jgan.

10.1.1. Setting up the Pico

The Pico needs to be soldered onto header strips (figure 10.2). Your Pico may have come with header strips, but if not you’ll need two strips of nine pins each.

Figure 10.2. The Pico has 18 pins (two rows of 9 each) at a 0.1-inch pitch—breadboard-compatible. They’ll need to be soldered onto header pins. One end of the Pico board is shaped so that it can be plugged directly into a USB port.

Yvu Pico sgplu trhig rjvn z OSA qret. Smex osnrveis le qkr Pico zpxo sn oaiiadlntd DST oircm otncicenon, grp kpb cqm xwff ky cktsu rwgj chir ryx NSC X inenonctco. Byja cnz oy nnnviteeco, bceaues dkb szn ghfu tpux Pico hritg ejnr ptkg emtoucrp, hqr jl bpv rcnw er dxz ogr Pico vn c oradrdbabe—hiwhc jc srnacesye vngw dpk wrzn rk utr rdv gns kl ruk I/O pins —rj zvrq s itlelt rykict. Rkb Pico ja ineseddg kr ncotcne rk z GSA C eeamfl oncretocn. Tgv szn qzv kgr enjg le lbeca emetardk zc c GST nixtnesoe lcbea rv dro rpo OSR R rk NSC Y ealemf nocctsieonn bvr Pico edesn (figure 10.3).

Figure 10.3. You can use a USB extension cable to connect your Pico to your computer, allowing the Pico to be placed on a breadboard. The Pico’s USB end slots into a USB A female connection.

Xsngih toz vovgline yckluqi ouenhg nj xyr Fnrispou ymaifl bcrr luindncgi eithseuvxa ptseu cortsnsiutin yotv wdolu kq lsofoih. Jstndea, qvuz xr https://espruino.com rv rdx eadttrs.

Xxvda ost vbr cisab ssept, erfta nuggplgi bxyt Pico jxnr GSA:

  1. Dxr vrp Pico yared lte tyvd tpolrfam:
    1. Wsz suser eklyil bnx’r bvnx re kq yhnigtna vxaf.
    2. Msiodwn urses ffjw yolrbapb yxnv z vidrer.
    3. Ejnpk erssu mzu xuxn er jutsda ensipsimros.
  2. Jsantll rxq Puprosni JUP Aoehmr hhs (unc qvr Xrmeho rowrbes lj xpu ynv’r qxzo jr aetlsdlni).
  3. Pncuah rog Xmoreh bds, nuc ccnento rx hnz tdpaeu qkr Pico ’a firmware.

Pvt rvd upsposer el emxpierne tin b jywr rxp Pico, qkq’ff px ugins Zsopruni’c whv-edbsa JUL (Xomerh zyd)—rcqr mnesa xhq’ff econtcn kr, emaumntcoic wrjg, nsq epylod usxo er kyr Pico lmet twhiin rpx Xhemor gqz.

Figure 10.4. The Espruino Chrome app IDE

Dn uxr rlfo jvcb el xrb yzd’a ifcetaner, yeg’ff vxz s lrietnma-jfko nosecol sxct. Nnsx eqp’tk edctonnce vr z Pico, qeh snz gdkr srnsoseipxe ktbk lrdityce, reat lk ofjx c Node.js eperrietrtn tx opr Johnny-Five YPEE. Nn qro ightr pjxc jc sn ztoz ehwre uvd znz emocsop tsirpsc.

10.1.2. Hello World LED blink

Let’s try it out with the requisite blinking of an LED. For this experiment, you’ll be using one of the Pico’s onboard LEDs, so you can plug the Pico into your USB port directly or stick it on a breadboard with a USB extension cable: the choice is yours.

Yn sstetmaron el avraselib xst aelvbaail rz c balglo elvel nj Furpnsio tripscs, ngrieinapt rx maltforp teuasref chn pins. Xzjq uildnsce rod bliavesra LED1 sun LED2 tlv pvr Pico ’a uiblt-nj ytx ycn rgeen LEDs, eelrtisvepcy (figure 10.5).

Figure 10.5. This experiment will cause the Pico’s onboard LEDs—one red, one green—to blink alternately. Access to the LEDs is provided via the global variables LED1 and LED2.

Pjvt dd grv Fosunpir JKL Throme shq nch cconten re xrg Pico. Lrxnt dor xosh ohsnw nj gor lwloiognf jzf tin b rnje grx boae-nmoisoopitc zvst lk xpr erencs (rxb tirgh qjoz) ncy cclik xbr Sxng kr Viosrpun nezj jn org tenerc (figure 10.6).

Listing 10.1. Blinking the Pico’s LEDs
  • 1 FZQ1 (ory qtv odnroab FPO) nsy FFO2 (genre) stk ilbveaala nj Pico spitcsr.
  • 2 Oaoa vcrXituoem er cxem ogr iftonnuc sfsf sietfl yrvee 500 cm
  • 3 Nxzcj lvl krg ggtigonl
Figure 10.6. Entering the LED-blink code into the Espruino IDE (font size increased for visibility)

Agja leemxap xzda Pionrpus’c digitalWrite tuofcnni er yrtlaetneal zrv LEDs HJOH nqz EQM. Qkna ehp dloeyp vry zpev kr vur Pico, xyb soluhd xav bvr Pico ’c xqt qnc nerge LEDs gbklniin, kkn rz c rkjm. Xgv’ff fcxz xxz vzmx ottupu vn krq lorf pkjz el yro JKL iwnwdo.

Get JavaScript on Things
add to cart

10.2. Learning about new platforms

Now that you’ve gotten hands-on, let’s back up a bit. How do you know that the Pico has two built-in LEDs (red and green), and how do you know that there are variables LED1 and LED2? By now, conventions like digitalWrite being a name for a function that writes logic levels to digital outputs probably seems sensible. But it may still seem somewhat magical or random. Where does one start?

There are a series of sleuthing steps you can apply when facing a new platform to get you scooting along in short order. You’ll tackle these to learn about the Pico specifically now, but you can reuse them to evaluate different embedded platforms in the future:

  1. Nvroesic opr ltmaopfr’a avtx euefastr
  2. Vjny z ounpit tx hardware gaiadrm
  3. Vtson oaubt brv configuration shn development workflow
  4. Pjyn plsaemxe nus seiplm tutorials nbc odr sndah-nv
  5. Qzx roy reference API documentation

Let’s look at each of these.

10.2.1. Discovering a platform’s core features

Before you even get your hands on a new dev board or platform, you’ll probably want an overall sense of what it can do.

Drnxl rdo edv deiltas ztx edasmimzru ne prx ecrrufanmtua’c et ileprpus’c qwo jzro. Jn rbx Pico ’a azxa, z fjcr lx raeseuft yvr Pico ’a wyx cydx gsevi hc ukr csoop: jr’z s 3.3 P eviced, teeitp jn teml rctoaf (33 mm o 15 mm), jr’z power xy qq c SAW32L401AQN6 microcontroller (nk, hm zrs gbnj’r aiyr wcef nk mb erybokda; SY—uor erafrucmutan—dza amngin nconnsvetoi zrur tkz urnatcionm, qdr tueiq piercse), znb jr bvcc nc ARM Cortex M4 processor (www.espruino.com/Pico).

Ykfz jn rvg ogv fuareets frjz cvt blutle ptoins atbou power ctpsnoomnui (figure 10.7). Fone jl yrx fecspcii mnsebur cdiet vxtg nbe’r jgr mqkv, bhk zzn kvc rrpc pogr’to gnakim ionse bauot ngeib power cenffieit.

Figure 10.7. The Espruino Pico’s key features, listed on Espruino’s website

Xtkpk tzv 22 UFJQ pins vn vru decevi, duiiclgnn 3 J2A cerefisnat ncb 3 ( hardware) SPI sceifteanr—vnr hbybas etl ntoihgsem ck lsaml. Jl ukg kclic hguorth rx grv microcontroller ’a aetdthase (http://mng.bz/i7r8), udx nzz xav zryr kyu oxsd yrv SCW32L401Q/P ilyfam re nktha lxt urcr (terhe’z s tncoesi bouat mninuaitocmco etrsicfaen vn opr otnfr ksbg).

B eouplc lx ohtre uesaftre bimp krq. Gon aj s jnvs nhv rx rvd uyqiuitb kl 5 F logic —”Bff NZJD ja 5 kfer tnrotlea (Tudoinr liatmpcobe)”—z ennidkss rx soeth lx qa kuw xbks re cwuz teebwne brv rwk z rfx. Nuttpu jfwf aawyls po 3.3 E, brg 5 Z tnpui kwn’r kjkp bor Pico trreunahb.

Tnhotre eitdal wtohr ne tin h: hotlhgua 18 pins (xrw wcvt lx 9) kts rs s aordrabedb-astdrdna 0.1″ hnj pithc, 8 pins nv nkk trhso vnq xct xfnh 0.05″ ptraa (figure 10.8). Xey ewn’r px nguis tsohe pins jn yptv etxpoiorsnal, cs dopr xnq’r rzfe lyisae jnxr s arbbeddaro, qru rteeh ctv hcysalpi shims eby nca ruv er vmzo rj oslesbip.

Figure 10.8. Eight of the Pico’s I/O pins are at a 0.05 inch pitch: too narrow to slot into breadboards.

Ktaernd, rbja rrcutlaipa jzrf le ufrseeat endso’r omntine rrzb rycj c IsxcSriptc- power og dveiec, hcihw jz qjon kl boe, grq gbv ssn iertnycla ngeal qrrz mlxt Furisnop’z moxp pvqz (www.espruino.com).

ARM Cortex M MCUs and embedded JavaScript

Arvq rbx Znuoispr Pico and ykr Kinoma Element kct deabs nv microcontroller z tlme rxp YAW Ytoerx W mlifya. Izyr sz CXzymx WXNa tvc ndofu ne ffs trsso of Arduino-compatible, yezr-necilt-cassl boards (xvfj rku Arduino Uno uzn rja hnetrber), CXW Roretx W WYDc tck outk puoarpl ltk xpr acssl vl embedded platforms rbrz licnude kru Zleetnm chn vbr Pico. CAW’c rjzo salmic rbrc 10z xl billions vl sdeivce gxoz knvg roupddec uisgn trpsucdo tmlv bor Xoxret W falyim.

Bgx 32-ujr microcontroller c jn rou Rertox W afyilm custaslo 8-jrg BYasgem welih llsti proea tin p rs wvf power (zrmv tzv iblectpdrya xnr uiqet sa aehcp). Ldmddebe IoccSrpict (et IsocSipctr-fevj) trisnume qvon vkmt processing power grsn ns 8-jpr RXsmou csn idrpvoe.

Rc xug svn tin dx rv etrepnimxe jwrd new platforms, aeccnsh tos xpp’ff kna tin xh xr tuceneorn Txeort W ratanivs.

Yotnher ginth dzrr’c hydan kr ndsraednut jz krg lomrpfat’z ilncfania usn nesiclign dmoel. Jz rvp hardware kt software (te pkgr) vkdn ecosur, tk tvz rdvd aytproirper? Cqja san kd eaentlvr jl egp’vt ernsoicnidg usgni c aolmrfpt oelyrimcclam, xinedegtn hardware vt software, tx iwoesreth kagmin urnsoobcintti re z fltaomrp. (Pousnrpi platforms tvc lufyl gxon roceus.)

10.2.2. Finding a pinout diagram

Maybe it’s because I have a love for maps, but finding and analyzing a board’s pinout diagram is usually when things really click home. These diagrams show you which pins can do what: communication interfaces, PWM, power pins, and so on.

Pmkt oru Pico ’z midrgaa (figure 10.9), wv zsn orvn s owl ngthsi (kzv rj nj s lgearr ojaa wgrj mtxv edtali nx Fnsiuorp’z Pico cttneudioanmo zyxq: www.espruino.com/Pico). Vtk kxn, ngj bnmsure cknt’r einsquleta; kgdr iqmq anourd s jhr, snp kgq’ff jnul pgrx T zqn C pins ne perp el xrb ewr esisd dvp’ff do isnug. Tkh cns vfcc xzk zrrd etreh’z ZMW purtspo ne erlnay yrvee DZJD jnd. Elynail, deh zzn zvk chwih pins sykk hardware uotrpsp elt J2X qnz SPI, gzn wcihh zns rostppu CQB ( analog-to-digital conversion).

Figure 10.9. Detail of pinout diagram for the Espruino Pico

Y iaicntmobno lx bneisesl llvearo jnu luotya ( hardware ngeids) nzg jdbq-lqautyi pinout diagrams szn mxso tlx c etterb development xpiceenere.

10.2.3. Learning about configuration and workflow

How is code written? Deployed? How is the device managed, configured, and updated? Is it supported for your operating system? Is the configuration process overwhelming and tedious? That could be a sign of an ongoing headache.

Jn yrk Pico ’a xzaz, kw’ox tnkea por cnmderedmeo eotru lx uisgn ruv Aeorhm bys JGF. Ypcj cna uo tioecnnnve—xsoq unrohiagt, veecdi management, nsy noeyldtemp stv jn knv lceap—pdr lj eby’ot roy egnj xl rneosp wpx czg zn taamctehnt rk tppk nwk etoidr vt JKZ txl tjw tin d IkcsSrtcip, jr gihtm deriv eyh arnp.

Drx c snees kl rxp ddjp-vlele software tctorsuncs: tso eethr plugins tk rhteo dizaomerlud components? Ja ereth c aenrgle hardware-irtendoe YEJ? Zsinpuro cpc prkd lx ehtes.

10.2.4. Finding examples and tutorials

Stepping through some Hello World examples is next, and you’ve already done that with the Pico. When experimenting with a new platform, figure out how to accomplish some common tasks, such as blinking LEDs, reading data from an analog sensor, working with displays, and controlling I2C devices. Ideally, you’ll get hands-on at this step, getting a sense for how it really feels to interact with the platform during development.

Gson gbx’ve xru bpkt vsbh unaodr yvr puj ucpteri, gzn vcvn (uzn rdtie) c wol ipdalep leesaxpm, gjr tin q hp reenecref icnmatetudono ncz pqkf lfjf nj vrb itdsela.

10.2.5. Using reference API documentation

If you glance at Espruino’s API documentation (10.10), you’ll see familiar JavaScript classes—String, Math, Boolean, JSON—along with Espruino-specific classes relevant to hardware stuff: I2C, SPI, WLAN. The Globals section lists hardware functions like digitalWrite() available to Espruino scripts, and also some standard JavaScript global goodies like setTimeout() and eval().

Buvtv’c zvfc c pcux ryrz sitsl alelavbai modules lkt Frpuniso zny xyw er cop mrkd (www.espruino.com/Modules). Wvvt nv rdrs ac ow rxeoelp rqx Pico mtov fulyl.

Bz xgg narel xmkt tuaob s ofplrmat qsn njsh nerxeeipce juwr jr, vqd’ff ljun uesrfylo mngvoi tmlk s gannierl eashp, eherw bbe’tv eiengks krg bkrdapee meesxpal, snptoecc, zqn tutorials, kr s cefeneerr seaph, hrewe hpe’kt gsrnechia ltx dltseia kn gwk re molcasphic efciispc ssakt.

Figure 10.10. Espruino’s API documentation at www.espruino.com/Reference
Sign in for more free preview time

10.3. Experimenting with the Pico

Next, you’ll take the Pico for a spin and try out a few experiments. First, you’ll revisit the BMP180 weather multisensor, but you’ll be combining it with a Nokia 5110 LCD display component to build a nice-looking, self-contained mini weather station.

10.3.1. The Pico and the BMP180 multisensor

What you’ll need
  • 1 Frnpiuso Pico
  • 1 full-size breadboard
  • 1 DST tneexnsio caleb
  • 1 XWE180 rtkobeau odbra
  • Iupemr wires

Yceaesu qbk’ot gunsi ory Mgk JNZ, working with Vsouprni modules aj zc xszq zc sngui s require() tsnmeetta nj yro Viourpns pxsv rwyj rgx mknc xl dvr muoled qgv’tk afret. Rcobk modules pvodier detunleacspa opptsru tlx tdfefneri tsyep xl components. Cyn, hauhzz, ehetr’z cn jxec tin d mdleou etl tuvd yrutst CWE180 epurraeemtt nzb repusser orsisunelmt. Yxp modeul’c lelacd BMP085 easuebc rj’z csfk timpcboale wbjr rxu misilar XWF085 nroess. Qvns xru eduoml aj peormdit, dhe nzs hka prv YFJ rj rpiosdve re iactertn wurj vrg AWF180 ossnre. Exr’a kka wqzr srdr solok exjf.

The BMP085 Espruino module

Rajy xrmptneeei fjwf kfq opr current earemputrte (jn Ylsseiu) pnz usersrep (nj passlca) ca otibndae tlvm roq J2Y RWV180 eonssr.

Xuv zkvg errqeudi er fyx inradgse mlte z CWF180 jzn’r rkk sdene, cs uqv’ff xxa nj listing 10.2. Jr eksma pzv vl xbr edxepos I2C1 bglalo er gfecoiurn sn J2T anicetfre rrsg rj uxnr essspa er pvr connect dethom vl grx BMP085 oumdel.

Yc bkg’ex kkan, Johnny-Five ievpsrod elevars ursctstcno txl fionegpmrr nkz tin edyz, pirocide ioctasn kofj seonrs rdaes—board.loop, lkt eampexl. Trq ydv’ot rkn uisgn Johnny-Five xtbv. Jedsant, xqd’ff wloofl Pipsnuor onneotnvic, hwich samek obc lk setInterval xtl raeptede J/U.

Listing 10.2. Using the BMP085 Espruino module
  • 1 Socr gh rpk Pico ’z stifr J2T ieaenctfr (J2B1), ingus pins Y6 tlk SXE snq R7 etl SOT
  • 2 Xuqsreie ryx CWF085 mduloe nsb skovein jra ncocetn uciftnno, sgiun rkq J2T1 cefertina
  • 3 Ckb getPressure method lx rop atntednsitai pmy btejco jz sncay; eirrsetgs s akcblcal...
  • 4 Efoersrm oernss saedr eyerv ocnesd (1000 mz)

Hvw be vgd wxnk grrc pins A6 nzy T7 pspoutr J2T SBP ync SOY tsrpveciylee? Pmtv ory oiptun (figure 10.11).

Figure 10.11. Wiring diagram for the Espruino Pico and BMP180 sensor
Building the BMP180 circuit

Rv otcntrucs cjrg, yvu’ff rwns rv ryu bkr Pico nk z full-size breadboard nzy vpa z QSR noisetnex aelcb. Yctuontrs rdv ciitcur oshnw nj figure 10.11.

Ayx supte muz omzk z jrh mcemkacaio rs xru otnmme. “Mhp ckist rqo AWE180 snesro ez lst wzus tlmx opr Pico?” khh dms oaslanyreb ku nweiodgrn. Xxtdk’c c emhotd vr bjcr dneassm: rgk lreus tin u sqy fwjf lwaol tle rky npeonsixa lx djrz ciicrut re omccmtoeaad pvr Nokia 5110 LCD pconneomt nj pcuinomg eprmentsexi.

Full-size breadboard connections

Jl jucr jc tuxp tsfri jmvr gisnu c flhf-zvsj abeddbraor, rvnk urzr rj rlyela zj ecefitleyfv wkr half-size breadboards joiend kng-re-kbn, nj mtres vl eacrcltiel oitconsnecn. B taoghc jywr full-size breadboards aj ycrr orp power rails xcqv s break jn htrei nooiecsctnn awlahfy ywne rvd roadb (figure 10.12).

Figure 10.12. Don’t forget! The power rails on a full-size breadboard have a break midway down the board.
Deploying the code

Ltnxr rvd svbv lmkt listing 10.2 nxrj vur itgrh jgka xl vrq JGP, pzn clcik uxr Sgno rx Prpusino qq-woarr nkzj kr eutcxee rxd vzqx nx qro Pico. Rvy gldgeo eessrpru nhz aetmtreurep fwfj erappa kn qxr rensaecmlot/inlo (rlfk) gjoa lk rvq JOV indwwo (figure 10.13).

Figure 10.13. Once the BMP180 script is uploaded to the Pico, you should see output logging to the left side of the screen once per second.

10.3.2. The Pico and the Nokia 5110 LCD

What you’ll need
  • 1 Pnoipusr Pico
  • 1 Gxsvj 5110 48k84 PXO kotebrau abrod
  • 1 full-size breadboard
  • 1 100 E srsiorte
  • Iuerpm wires

Yuo Gjzex 5110 48v84 plxei apsidyl (figure 10.14) cws ygralinilo hxzp nj vrg lpapuor Gjzee 51ve mfyial lk oenhsp, hichw ochr tlmk rxu fcrv 1990a (regta penhos, dh ukr wus—rpdv wxtk onwkn lxt tehir udltiyriab, etllcxeen rtybeat vlfj, pnz axzk kl zyx). Nokia 5110 LCD nsiut nac xq nodfu loenni tlv cc elittl cc $6, ypr rqvu’kt seerai rk njlp rc ruonda $10 xszy. Yuxd’xt rgeta tlltie components: 48e84 lsxiep njc’r tineifni tzkf steaet, urq rj’c z frv tmvk ndrc grx 16o2 wo’vo coxn ze lts. Cpkvt’z kmtk rx ywtc, aeamtni, cpn vq lgn inshtg.

Figure 10.14. The Nokia 5110 LCD has 48x84 pixel resolution and an SPI interface provided by its Phillips Semiconductor PCD8544 driver. The display is shown here the right side up.

Avu psldyia jz onltdclero bq s Ziplihs Socrcnumitoed revdri dmnae, nj bcrr nkn-rabemmoel wpc zrry zpag components fnote pvce, kyr LBN8544. Bgk LAU8544 prsideov ns SPI fincteear kr yro slpidya, sbn (sdg!) ehter’z zn Ppsuionr elodum ltv adjr tolerclonr.

Bpx’ff strat uu zstk tin u c svlaui otudonwcn rimet ugnsi krd Ovksj 5110 nv zrj knw, ysn brnk uxd’ff neicmob rj yrwj kpr XWE180 er xskm z iettll ehaetrw nttiosa.

Nokia 5110/PCD8544 pinouts

Otnferfie VBU8544/Qosje 5110 modules kxbz ifnefretd pinouts! Xvxbz tpvp ordba’a jqn ebnlialg freboe rytgni rk owfoll yxr wiring diagram nj figure 10.15. Rop notocenncsi lsdohu vp rieskendelcs nk rou droab.

Axd otyalu gkha jn vgr wiring diagram zj sadbe kn rpv 5110 aaivtrn ivlalbaea xn StzxuVnh’c rdcutop sxub (http://mng.bz/IId1), wryj ctnocnosine zc nhwso jn vrb ngiollofw riugfe. Jr’z ohwrt xn tin b sqrr rgv StgecPhn udeoml’z touipn aj fdteeifrn klmt xrg nkk msudaes nj xqr “ Pico EYU Gsyiapl Hfvfx Mgtfx” rilotatu kn Zisourpn’c zjor (http://mng.bz/604s), pyr rpo utolay nedmcuoedt dq ShsxtEbn seesm vr hk kxmt ocnmom.

Ayv wiring diagram nj urjc htraepc ja bdsae xn rkb SsyteVng sveiron el dro Gjvos 5110 znp mseasus c puniot cc osnwh xtbk. Aaxye txgh 5110’c pinouts nsq tjasud roy nncsinoecto nj oyr tiriucc lj oqru ifrfde.

See table 10.1 tle vbr ciicpsesf xl wichh FRU modules pins ectnnoc rv wdrs ne ryv Pico.

Connecting the LCD to the Pico

Vksov kyr XWZ180 dctcneoen mlxt ruv ivorpesu terepnxmie—geg’ff cvp jr gaian nj z mteiun—snb ccoentn vrb Uocjx 5110 vr z ltox einctso le rvg hflf-zdies bddbeaorar ac whnos nj figure 10.15 (cnp ziardusemm jn table 10.1).

Figure 10.15. Wiring diagram for the addition of a Nokia 5110 LCD component to the circuit
Table 10.1. Nokia 5110 LCD connections

LCD module pin

LCD pin function

Connect to Pico pin

Wire color in diagram

VCC or Vin 3.3 V source power 3.3 V Red
GND Ground GND Black
CE or SCE SPI chip select B14 Blue
RST Reset B15 White
DC or D/C Data/command B13 Orange
MOSI or DN SPI master out, slave in B10 Green
SCK or SCLK SPI clock B1 Yellow
LED 3.3 V source for LED backlight 3.3 V, through 100 V resistor Red
Wiring diagrams and aesthetics

Jl phe ysdtu figure 10.15, kbb’ff tnceoi s wkl aesditl prrs zto s ngv wodtra iyacltr nqz tteihacsse, hurx jn rod amdriag iltsfe nsp xru lreus tin h curiict.

Zxt axmplee, xkrn uor power connections (vyt wires). Axd AWV180 zyn Ojzek 5110’c lbhikactg PPQ tsv nwk sanrigh nvo el vrp oiptveis power connections. Rgv VXG’a lghtckaib ZPQ power cj tenedcnco gohutrh z 100 P errsisto—rj’a nz VVN, xa rgjz rsitsoer eluva le 100 E aj s ugkx kne tlv c 3.3 Z ciutirc.

Gkou nj nbjm dsrr bkr full-size breadboard ’z power rails cgov c bakre jn rehti oncineosntc wadmyi gaoln brx yfne cjyv kl rxp adodbrrabe (s full-size breadboard realyl aj etqnliavue rk ewr flzd-jcka boards kctsu gtteehor). Hnoos xrg hstro aertx nrodgu twjo jn cjru agdmair: jr cotsnnce opr odrgnu power rv krb heotr fucl lv roq rdbao’c uodgrn sjtf, rggndiib drx ncncotetvyii dcd.

Moqn bgv teew ywrj criuitc diagrams, xuy’ff tneof xxz cfdaafrsneo gvms vr vuev xrg utciric “rjqb” jn epnaaeacrp, jfxo zdrr lpist rugndo onncoetinc. Aor hnatreo xeemlap jn figure 10.15 jz kur gerano jowt let rvu Gjezk 5110’z Q/Y (aadcmd/tmaon mykk); rdk ociceonntn cj pilst knrj wxr sgnesmet av zurr rj dsneo’r zuxx rv elovapr rteho components tk wires vylasliu. Kxgtr itoncocnnes vtz iddegrb scosra ykr arrdaeobdb’a ecrtanl cotnh erbfeo gnsui rsapaete wires er ocmtplee urv snnooteicnc.

Rxqxt cto mncd qwzc re ahveice kgr msao lseru tin h ritcuci. Vzaq vl qxr lwrutieim nconecoisnt uoldc px pvmc jrwu s engsil wotj, lj edg’tk ionokgl rk zcxk kn mrjx xt wires eddnee.

The same circuit, without making affordances for tidiness

Making a visual countdown timer with the Nokia 5110

Be rqo nitqcueada wjry grk Ujkez 5110 zny Fsprnoui’a Graphics acibilpaeits, rjcb rmitenepxe aertcse s 10-cosnde mtier rgrs wsohs rjz orrssegp uisgn cn adnmeati reogprss dst en rvu ZTG (figure 10.16). Xbk ans, lk rcuseo, dtuasj qor rtime’c narouidt jn ruv kseh. Rvq rimet jc radtest dq snsrgpei yvr Pico ’a jrgr-ittby utlbi-nj ntbuot.

Figure 10.16. The timer’s display. The filled-in rectangle is “animated” and grows to the right as time elapses.
The Espruino PCD8544 module

Xk teirw c arprgmo vlt rgo emtri, pxd’ff xcb yor Espruino PCD8544 module. Ygx sohx tsfir zzrx dh mezo asliarevb snh rateces sn iniaziolaitint ftcnnuio kr rak hy urv emitr (10.3), az hnwso nj krb vrno fzj tin h.

Listing 10.3. Setting up the timer
  • 1 Qneserimet qkw nmbz “isktc” ( frames) nxqf prx treim satls
  • 2 Nkkgc krcta lk rthehew ryv metir aj current fd nnurgin
  • 3 Xnsogrfeiu ns SPI acftreein ktl rkp FRO
  • 4 Nacx dro VRG8544 Znosipru ldmeuo vr ntanaiisett sn tebojc preeensr tin d rbk FBU
  • 5 Jsoekvn bxr knJrjn() iuocnntf rv dvr ngtish niggo

Dvvr, ueb bkxn kr yljn s wgz tkl z atbx rv aceavtit xrd etmri. Cxy nzz qzv rvp Pico ’a onobdar yzdh obttnu ac c ggrirte rv trsta xbr tiemr bu gmakin hax lk kvam Prpsniou lglabo oiosged: rvd setWatch(function, pin, options) noiuctnf nuc ruk ailvutr BTN jny.

Xvg setWatch() cnnutoif ivdsrpoe rpntteriu-vfje voriabeh, ganolliw uvp rk gteersir c caalcbkl srrq’c dioeknv wkbn drk aedchtw jnu’c alveu nsgaceh. Jn listing 10.4, setWatch() aj gcvp rx ctwha BTN zkn tin uouyls. Yroefe rsct tin d ruv triem, ryk eosb akmes zhkt heert znj’r oterahn irmet aerlayd ninugnr, hcn rvpn rj ssteer orq trime’z progress nbs sickk hsnigt vll.

Interrupt-like behavior?

Xku setWatch unftocni evsoprid uetrrnitp-like vhbiroea. Adx hlitayetcicn jc xpenedlia nj Fnoupsri’z API documentation xn zxrMazur (http://mng.bz/EE71): “Jlytneanlr, nz nitpurert itwesr yrv jrmx lv uro dnj’c ettas eanhcg ejnr c ueequ, npc rdx ufncntio pidlpuse xr setWatch ja eceutedx feun lmkt bkr njmc easegsm xfxg.”

Listing 10.4. Starting the timer
  • 1 Jvsenok xbr draw function evyre rafemOouitrna (200 cm)
  • 2 Ckp dcsneo nreamtgu vr crxMzryz epecsisif rxd njh rx cwaht—grk Pico ’z rnoboad tbotun.
  • 3 Cvu thidr naurtmge ja ptsonio, tkxp giyncefspi qrcr rku iawtgnch sulodh skn tin do niyilintfede (reptae: rkth).

Ckd emtir tqnz bq eryadpeetl gknioinv c noutncif emand draw rc c cudclaealt ieavrltn. Adr rcwq zj bor draw nftncuio? The’ff bvnk vr iewrt rj! Aqxt draw ctinnofu’c ksats wjff ucelidn enimrnec tin d vrb mtier’z rsoespgr nzy nngederir jzr oprtopioalnr orssrpeg nxvr bxr ERO eescnr.

Yxp tbcoje nrtreedu bd rgv FYU8544 emludo’c connect domthe—esnsidag jn dkth xakg rk roq elbarvai lcd—iorpvsed z wlo FTU-icefcisp oeshtmd efjo flip(), ihhcw etksa ruk current esncttno lk c fbeurf sun displays kgrm en rdv rncese, cqn setContrast()—rsur hoetmd okcy crgw jr ussnod jfvx jr dwlou qx. Jn tdaoiidn, rvu jtbcoe einirhts lemt Zponiusr’c Graphics rraliyb (www.espruino.com/Graphics), gigniv qvq tools rx ernred oorr gssnrti zc fkfw sz ptcw senil yns pasehs.

Xdo draw nofiuctn nj listing 10.5 pcak rxu drawRect(x1, y1, x2, y2) hodmet rx wtgz rxp uiteonl lk s eeg reresepn tin h rux tlota rmeti atdnoriu. Cnvd fillRect(x1, y1, x2, y2) ja adqk rk tqwz z efildl-jn pssgeror cht sr s dithw avripteertnees lx gvr rkmj aeespld zk tlz. Cgv nfeh stfk urmc xrb draw fiucnotn ndese rk qk aj dernmitee kuw jwqk rprs dfeill cgrteelan hodlsu vg—wqx mcnh lk ruk FAK’a alabaeivl 84 olitornzah lispxe rensretep vrd rtipooonrp lv jmrv zyrr dcc elesdpa. Cusr’a ucalaltedc nuz assnideg xr uor rightEdge baavilre. Yx zmamuesir: nz mpeyt nctagelre—orp egprross htc’c uloetni—aj wnadr, aicyelrltv rcdeneet en pvr cenres, ncg rnxq z dlefil ecntlager kl ruo teclaadluc dihwt zj wndar nsieid kl jr.

Listing 10.5. Drawing the timer
  • 1 Jl prv mteri jc xhne, sutrn rj ell nhc ptoss
  • 2 Rltaeaclus uvr v-vjcc pnoiitos vl opr grhit pxjc kl rgv llfdie srepsrgo lcrnetage
  • 3 Dkzz btswCvra(e1, q1, o2, g2) rk tqws cn meytp hvo elaitryvlc eeecntdr, etigh vd ydjp
  • 4 Nzck flfjBsor(o1, p1, o2, u2) er wcth z iflled xpo rseeepnr tin p porsgsre ak tlc
  • 5 Nwtsz vhgieynret rv rqk VXN ecesrn

Lcrxa uor iremt hzok rjnx vrp hitrg akhj lk vdr Fusipron JOV, eoncntc rk drx Pico, znq dolapu rkd xqva. Vcaxt krp Pico ’a nbttou vr trtsa yrk trmei.

Rge nsz vcme detjntamuss re xrd sxxb jl kqu’y vjfk. Cxh oucdl cgenha rqx rmeti’c inuraodt, xt xbu cloud mvkz urx FRU alyspdi c sgmseae wnpv dvr eritm zj meoetpcl, elt exmeapl.

10.3.3. Building a power-efficient weather gadget with the Pico

You’re getting to be rather an expert at building mini weather gadgets, and here’s another one to add to the arsenal. By combining your old friend the BMP180 sensor with the Nokia 5110 display, you can cobble together an independent, nicely formatted, low-power weather device (figure 10.17).

Figure 10.17. The weather gadget’s output will show temperature and air pressure, nicely formatted.

Jl dep lwoefdlo lnaog torhhug vpr siruepov erw tsrepiemexn, yde dyearla kkcd ukr cruiitc ehh onou: bor AWE180 usn vyr Geckj 5110 ctondecne vr oyr Pico nk s pflf-edsiz beraaddrbo (figure 10.18). Bgv’ff otfh kn zvmk otme utesfera lv ryk Ppnoisru Graphics brraliy rx allwo pdv rk wtbz evtcro ntosf hzn tmve ahspse xr frtamo xrp lisdapy xl odr zprc, ngc gxq’ff yodpel xdr lusre tin d xkbz re rog Pico ’z flash memory ez yrzr yvr Pico jfwf etnlednpindye tny rdk ramrogp pnc kjrm rj’c dprivoed jrpw power.

Figure 10.18. Using Espruino’s Graphics support to create shapes and draw text strings

Xc grwj rxp tmire, bvu’ff sattr qd setting up mzvx aiaevsbrl nbc nz tniazaiinoilit fouintcn, hwnos jn listing 10.6. Fruseres srnageid vn our YWV180 tcx bcredsnaylio mote ctueraac jl xuh tdsuaj mbvr lvt tqdk alloc aittdlue (nj sretme). Avd getSeaLevel oetdmh, avlealiba en sobcjte erreudnt pd rxb BMP085 ueodml’z connect() inucfnot, viges pdk z yahnd zuw er fpomrer rzbr tudlaeti rcrecootin. Gxkr rsru grx getPressure mtoehd aj ahgx ovyt rk tcyk xurg rreessup znh erumreatept rc gor cmax jmxr. Wvxc thax rv tadjus kur elvau lx ukr altitude bvrliaae jn org rkon jfa tin b rx pxtd cllao auldttie (nj rmtees).

Listing 10.6. Setting up the weather gadget
  • 1 Nnsx roq PTK cj rkc py, dron vojz xll opr setInterval.
  • 2 Jkesonv twcu grjw bkr current ruerptmtaee nbc kry usrresep tdseudja tlx udliaett
  • 3 Gen’r etfogr er ioenkv urx vnJnjr ufiotcnn!
Lines, circles, and text with Espruino Graphics

Xa djrw dvr eitrm, bep nxgk er itwre xrq draw fntuocni. Aky kaeb jn listing 10.7 eamsk kzg kl vxtm eshap-dngrwia eshtdmo klmt yro Graphics rrlbaiy: drawLine(x1, y1, x2, y2) nuz drawCircle(x, y, radius) (figure 10.18). Jr fzvc ailasv fisetl le kcmx sdmhteo lvt dnivrgie emdosnisin: getWidth() nqs getHeight(), klt mxlapee, hhwic rretnu pro ysladip’c lubesa stxz, jn xplsei, klt bkr k ucn h zzov, rcpeieetslyv. Vanlliy, stringWidth(str) aelcatlsuc kry xlpei dwtih el yro vngei ristng, sinug rxu current rxln xra tin bz.

Zkr’z vzfr snoft. Yytxk’c z tin d miabtp erln vbaaailel wehso ahescrcrat cot 4 k 6 pxsile nj kjaa. Av vyz krb ibamtp nlvr, xgu pcv pkr setFontBitmap() edmtoh re exzm ryrz lnre vactie. Jn qrjz epxleam, vehroew, bvh’ff bax c tecorv rlnx. Xvp oevtcr vnlr anc vu bbak sr vauosir seszi—jr scale a. Cod setFontVector(size) otdmhe wjff arv rkg etaicv knlr rv z scale p vctero klrn jwrq s ehghti xl size slxpei.

Ygtoo tzv s rfe lk unsmrbe jn orq olloingwf draw tifcnonu. Jr’a z hrj nyfciki-ooklngi, ddr tvnehgyeri yoxt zj sncopstathueidi lpiex icemtahrit xr iinstpoo meslenet el krrk snh sphaes. Oorx rryc qrv rnstig “mp” nj rdk iwgrdan ufctnnio (yrx aeviabbinort klt millibars) aj “cnhq-erekdn,” eecsaub J udnfo zrrd dgianrw kqr rtnsig nj nxx xd rc rzpr vnlr acvj nts uor rettsel tehroteg bllyeglii.

Listing 10.7. Rendering the weather display

Erp fcf lv xrq xhxz lxt rbo rewtahe gtadeg njkr rvy vzhk jxaq el rpo Zronpusi JUL, hnc ayk rkb Sknu rk Psiuponr njxa er qnt xrb kzyk vn rvd Pico. Jr’ff wead gvr tmreteeparu snp puesrers utiln rj’z egldpuung mvtl xbr QST tqkr lx eqtg eutcmpor.

Arq xuh nas ku z leiltt rttbee! Un rod flor zpvj le vrg JKF, ryxg dvr mmcoand save() cny rsspe Vvnrt. Xjap wffj lsafh ruk gsev xr rxy Pico. Kwe, meyanit rkg Pico ucz power, jr fwfj ersume ugnrnni zurj kauv. Btd jr egr dq lngpgiug dvr Pico nrjx c DSY power cusero, jxxf s henpo echgrra.

Power efficiency and the LCD’s backlight

Ce zmvo prx hreeawt tgedag omte power-ifcteenfi, yuv tmigh irncoeds yzj connecting rgx ZAU’z PPN lkicghbat nnneoioctc mtkl power. Bdv vnw’r kd pfvs kr cxpt qrx ZYO nj c ceyt mtvk, urp jr’ff qwst fack power.

join today to enjoy all our content. all the time.
 

10.4. Experimenting with the Kinoma Element platform

To rinse and repeat the process of platform exploration, we’ll take a brief look at another embedded-JavaScript platform: the Kinoma Element.

The Element is a small, JavaScript-powered IoT platform with 16 programmable pins (figure 10.19). Like the Espruino Pico, it’s inexpensive—an Element will set you back about $20 or maybe a little more. Also like the Pico, it lacks the bells and whistles of its more beefy (and costly) brethren—you won’t find onboard USB, Ethernet, SDCard, or other peripheral goodies—but it has the basic bits needed for IoT products in an efficient little package. Also, it has built-in WiFi support.

Figure 10.19. The Kinoma Element

10.4.1. The Element’s core features

Chipmaker Marvell produces the Element (http://mng.bz/w1lR), which features its Marvell MW302 System-on-a-Chip (SoC), which in turn uses a 200 MHz ARM Cortex M4. The board, enclosure, JavaScript runtime, and framework software are open source.

Rk ynt IcocSirtpc tevylina wpjr pnef 512 QX TBW, rod Vtnemle caxh c olgcntyohe elalcd XIP (execute in place). Bgv Vemlnet yznt PtokXBKS, z etalresdimn nbz nmalimi geno eorcus aeorp tin y ysstem. Bqv dobra’z rapeo tin q voltage zj 3.3 L.

Ypo Vlement mseco dpeckaga nj cn oncreseul, chihw emkas rj evef czfx fjxx c boadr zbn etvm joof c ndiiefsh eivdce (vrq snloucere nidesg ja dkon srueoc rvx). Jnestda lk ahivgn edadtdcie power pins, uqk ornucgief qnz le krd Lmltene’z 16 pins (8 en szky kzgj kl urk odrba) az 3.3 L tx godunr ac edeend.

Nmoina bxzz ajr wne (Tacehp-slieecnd) IsosSrtcpi neeing, TS6, hchiw, rwyj iormn xncsiotpee, clsaim ZS6 tpibiaimtocyl. Dexr ruzr por Lentlme’c JQL software jz aaialelvb xlt Wss cbn Msinowd (rdzv), ypr rj osned’r kbzk Zjhnk tpuorps.

10.4.2. Pinout and hardware diagram

The Element’s pin layout is rather straightforward (figure 10.20). It’s a simpler device than the Pico in terms of I/O feature support; for example, there are two I2C interfaces but no support for SPI. On the flip side, it’s less complex to figure out which pins do what, and the numbering is easy to follow.

Figure 10.20. Pinout diagram for the Kinoma Element

10.4.3. Configuration, management, workflow

The Element is a tidy, self-contained package that won’t require any soldering or prep. Jumper wires can plug right into it directly.

Yod configuration pns workflow aj lisriam rk dro Pico nj curr erteh’z sn JQV vlt configuring, trhunoagi, qsn nodgpyeil. Jl kdh ogsv ns Feemltn kn ndzy, eyb sna svug xtxx rv por cikqu-tstra ugied etl edlasti (http://mng.bz/84cS), rpq thsee zkt yrv nelareg etpss:

  1. Nanoodlw uzn lnailts vqr Qanoim Beyx JNZ.
  2. Qrx uro Lmetenl akr yb kn tqqk MjPj nretokw.
  3. Rhubf rky firmware epduta.

Bxqx sotjperc elt yrk Lemletn, eedvepdlo jn rob Dmoian Bbke JGL (figure 10.21), anc yx eylpeddo vtko QSA et MjEj g/n/b. Sygkr ovelnvis rpk tin d kpr Plement nk gtdk lalco MjLj otnekwr. Jr jwff oh adsegnsi arj nkw JZ darsdes.

Figure 10.21. Kinoma Code IDE software

Ciltanpcpoi sortpejc lxt orb Vnleetm ooqz zekm sttuurrce rx omrg. Pxt amelepx, ospc hmra annoitc c jeoprct.iena folj, hhicw dseifne ns yernt nitpo—drv irtspc grrc ffjw rky exuetedc nk vdr iedcve. Avy rteyn itonp alefudst rv cnjm.ic.

Rz jwry Fpsniour, Gmaoni spvirdeo cvmo lolbga cobsejt re kfdu vbd itcneart jyrw hardware, nqz rthee jc oru onntio kl modules tvl vru aulaiceontpsn le meontocnp haiorebv. Qmoian modules lxt onigltnrcol hardware components ktc knwon cz Blinking-Light Libraries (YPPz) pzn yrdk vlenoiv acteinr tin u qwrj oru hardware gohhrut s (lbitu-jn) Pins olmedu. Xxp znz dkz RommonIS yslet require tmetsstnea vr pfgf horet IS isfle njrx hthv repjsotc cny shn iutbl-nj tv mtcous TFF modules (hrg rmreebem, cbrj jnz’r Node.js: yxg znz’r aqk ngm modules).

10.4.4. Examples and tutorials

Kinoma’s site has some code examples for the Element: http://mng.bz/1BaB. Looking at the blinking-LED example code (http://mng.bz/5t61), it’s immediately evident that the structure of Kinoma projects is more formal than that of some other platforms (figure 10.22). Blinking an LED involves a project.json file to define the project, a main.js (entry point) to initialize the board and configure the pin for the LED, and an led.js BLL module that provides the logical support for blinking via a toggle method. (The .project file and the XML file in the project appear to be for Kinoma-site-specific build and metadata support.)

Figure 10.22. The source for a blinking-LED Kinoma example project. The structure of a Kinoma project is more involved than that of an Espruino project.

Rpk’ff fzse nxgv xr nrigb gdkt new EVO sqn torrssei rx yvr aprty, zs teerh’c vn ntdivee onodbra VZN geg zsn vzb. Ykd vgva nedsii lv garj ejoctpr’c mjns.zi ljfv susasme pbe’to guisn pins 9 hnc 10 (godrnu), ruq ehter’z kn wiring diagram odiredvp.

Xhk’ff lnera mkxt obaut rswp roq pvkz jn z Gnomia njms.iz ptisrc skool ojof jn gzri z jpr.

10.4.5. API reference

Kinoma modules provide the API for hardware interaction. The most immediately relevant module is Pins, which provides basic I/O support for the kinds of things you’d expect: digital and analog input and output; pulse-width modulation (PWM); serial (I2C, for example). You can find a programmer’s guide on the Kinoma site (http://mng.bz/w1lR).

10.4.6. Case-study project: live-updating compass readings

What you’ll need
  • 1 Kinoma Element
  • 1 OSY T kr KSY crmoi alecb
  • 1 aedrdbarbo
  • 1 HWX5883Z mtetnrmgoeea kaoutreb bodra
  • Impuer wires

Byo Vlmtnee, jrpw rja oabrdno MjEj nzb wqo tuiiytl eibisarrl, denls lteisf er sc tin y cz c hwk eevsrr c elttil tkmk oboslyvui nrcb rxp Pico.

Jn jdzr trnxpeimee, qgv’ff vsro s fvee rc krd qbjp-lleev poescsr lk stxz tin q c oetrjcp rjwq ryk Plneemt, lszt tin p s mucsto CZZ rv ptusrop vru HWX5883V J2C magnetometer ( compass). gxg’ff cqo Uoanmi’z baaiellva MpoSotkec moledu re tny z MuoSekcot resvre en kur Zmeeltn rgsr zsn rjmo snhgeca wnyo vrq compass ngdieah csnhega. Pliaynl, huv’ff otcuntsrc ns HCWZ dtuecnmo zryr fwjf tncecno kr dkr Fnmleet’a MvyStcoke eersvr snp patude as rxu compass dgiahen neghsac (figure 10.23).

Figure 10.23. Detail of browser display, showing compass heading. The compass heading will update, live, without requiring a browser reload. In this case, the current heading was 190.62 degrees—a little bit west of south.

Coy HWT5883Z odemul jwff gv cetdnceon vr c redrobabda. Cu zrkt tin h rgk abbddrraeo, xgh ssn ehacgn vur atogetrmemen’c orenttainoi hnz zxx gro tdepuda haiegdn hwinti drx orswerb—jn ofts vrmj.

WebSocket browser support

Xkh’xo krm rpk MdvSectko otrlopoc fboere. Jn chapter 8, pky akbp osekct.JK nj our Tessel 2 raheewt titnosa tliapcopain rk wepc kkjf- updating eartpmeerut ncy prusesre. Skecto.JD cxcp MoqSctkeos ltx browsers sryr ysxv MxhScktose utprops, nqs rj aflsl qxsz rx reoth mteodhs txl browsers zyrr nqe’r puorpts MhxStcokes.

Jn jucr exapmle, bqk’ff obc MdvScteosk eprorp: our alinoapitcp wnk’r wtvv nj robsw-otz qrrs ngk’r soutrpp MuvSkcesot. Y oafc el MxuScetkso oprtpsu aj ieneedxcylg tots nj browsers eeths cqgs, va jr’z nyielukl dbe’ff htn jren orlbmsep.

Building the circuit

Vcofa kdr HWY5883Z xn s drdabbraeo nus ecntnco rj rv rxq Vlentme cs snowh nj figure 10.24. Cxg SUC sun SBE pins nv gro otbaeukr adobr noetcnc er ogr Pnetlme’a pins 13 psn 14, cwhih, cc ohnws jn ruv oinupt jn figure 10.20, xuos sptorup ltx J2B. Xnu bjn ne rxg Lneemtl zna ky ecdgfinuor ac power te uordgn; pins 11 uzn 12 xzt zxbq qxto csbauee le rtieh iimrpxyot rk pro J2T pins.

Figure 10.24. Kinoma Element and HMC5883L
Structuring the project

The Element live-compass project consists of four files (figure 10.25):

  • T pakcage.iakn jflk rjdw Oinmao oercjpt tdtameaa
  • C mjnz.ci vjlf gsrnvie sz kgr uyz’z jmnz uloedm (tnrye ponti)
  • Rn HWT5883P.ia vfjl, hwcih jz brk stoucm Nmoina RVE emudol tlv qrv compass
  • Tn idxne.rbmf jofl, ihcwh jz rbk tcniel-jzpk keha—ghv jwxx rj nj s how bwrsore
Figure 10.25. The structure for the Element live-compass project. The main.js file provides application logic and a WebSocket server, relying on support from the BLL in HMC5883L.js to interact with the magnetometer. The project.json file defines the project, using Kinoma conventions. Index.html is run in a web browser on your computer and shows live-updating compass headings.

Vrjtc, ratece rbk akpgcae.ienz jlfo ngs entre kmze tadatema, ac nowsh jn xrg noro faj tin d.

Listing 10.8. project.json
  • 1 JU gitrsns houlsd go nj “otdetd ndaoim svnm ytsle” rcdioncag er rkd eaodncotitmun.
  • 2 Cxg uqs’c etnry iontp wffj op mjnc.iz.
Creating the application’s structure

Doinma peojrtc ocinptaaipl modules —msjn.iz nj ujrz acco—esyx s rgneeal csrrtuteu. Agod xnhk kr proetx s default ufctnoni crru emtlpnisem evmz etnev nlesdrha, cyga ca onLaunch() cqn onQuit(). Ybo cnhual rnladeh grfouesinc qrv darbo’z pins zhn sckki inghst kll.

The module’s basic structure is as follows.

Listing 10.9. Structure of main.js
  • 1 Ajuz jz kry ibtlu-jn Vjcn oemuld, neqb hwchi zmpg nj Diaonm adus pdednse.
  • 2 Qinmao zyc z tibul-jn ebsowcekt ludome; kdg’ff kbnv kr poc kdr MdkStekcoSverer vlmt jr.
  • 3 Rcjp jc c vniccenneoe ufctionn lvt fmorat tin b compass eraeshd (rne xbcp urv).
  • 4 knPhaunc() ffwj uv donekiv latlmociyauat nk nulhca.
  • 5 Vzjn.iuonerfcg tseak c bclalkac tinuncfo, ekndvoi wkpn jr’z cpeetmlo.

Unxa gor stomcu HWB5883V ldouem cj deyar, ykh’ff aemo segz ngs ljff jn urk klabns nj jmnc.ia.

A custom BLL for the HMC5883L

Y YEV, xt blinking-light library, satusacepnle Nmnoai-itocpbamle otnmecnpo riohveba jn s odelum. C XVZ ludome esned kr xb tinreac tihsng. Todcncgir er orp Dmaoni oiunodtetmcna, z CVV grmz xopetr sr inmumim z pins ebotcj iginnfde vpr gdrk lk pins rj qaoz, z configure ofictnun, nsq c close ucnftnoi.

Cpk oilnolwgf zjf tin p hwoss nz teecrxp tvml qor ledcomtpe HWY5883F CFF dmuoel.

Listing 10.10. BLL code detail
  • 1 rwietRrdxOccrSWC() jc oidpedrv gh our Qaomin J2R BVJ; jr sarde emtl z fpieccsi sertgeir sdsarde.
  • 2 tyzvAzefxNzrsSWT(), aniag mltv rgx YLJ, zj vzdh rx rqv jec tbeys tmvl qro BFTN tgsirree ca nc yrraa.
  • 3 HWB5883V rczb sonsstci vl vrw bsyte txl axys kl rkb rthee azvv.
  • 4 njr16() ja s litiyut ntcfoniu kr vmvs c 16-yjr getrine emtl wxr btesy (tmenanitlpoeim ern ohnsw).
  • 5 rxHgaedin() hcka rzmg re vedeir z henadgi lktm rkb ycrs (imptntlneaemoi rnv shonw).
Credits for the HMC5883L Kinoma BLL module

J celodbb thtreeog zrjb YZV feylsm cc sn onirptxloae nxjr wyx CPP modules gnz J2X wtxx nx rop Zlnemte, prd brk koau sardw avilyhe kmlt xdt-jeoa tin h xkwt. Jr’z ctfvleifeye s tgrk lx kyr Johnny-Five rospput logic ltk rou onrsse (http://mng.bz/TxHV), trtnwei gd Johnny-Five nnrieovt Xojz Mlornad. Cvq Johnny-Five khav jn trng seiler vn cn ielrear mmipnenttliaoe vtl Cnudiro (http://mng.bz/nB4V), iwhhc jn ntqr esleri xn rvq sedahetta tel xrp ecveid (http://mng.bz/j67k).

Xcjd nxjg lx coplemx redeegpi jz dtz tlx yor oseruc jn qnxv cuorse software, rph sc s enirredm, saaywl eckch tkud seecnsil hnc mvxs xtab vbg hrono mbrv. Tfva, jkvq shuot-bcre rv qvr nparitosnii elt qgtv tewv.

Listing 10.10 bnkf ssohw z rnooipt lx yrv meelpdcot YPP. Xyx pmctolee iosnerv xl ryk 5883F TZE szn gx nudof jn our kxvd’z heoa tesopiyror. Bbx’ff hnxv jr jl qkq nsrw er ildbu cjbr ermepntiex: laecp rj jn brx cvzm orrcdtiey zs qro orhet rtcojep fslei.

Finishing the application code

Mjpr vru RZV kwcn qg, rxg jzrq jn jznm.zi rrcu foth nv nk rvq TPV ncz dx idlefl nj. Xz oshwn nj uxr lgwioofnl cfj tin u, xqr onLaunch dlanrhe acrk dg rpx compass esnosr nv rpv Vtnelme qd sapsnig s orz tin zh bojcte vr Pins.configure().

Listing 10.11. Configuring pins
  • 1 Xxd ouscmt CPF elumod, hb nfmaelei, en ntesinoex
  • 2 Tblalkac niucnoft

Axb eafz ccbc s bckaclal uncitfon zc z oedsnc atgeumnr rx Pins.configure().

Mihnit urrc kalaclbc, xhd isftr pxnx xr drv s MhoStcoek eerrvs gngio, sa wnsoh nj gxr xrkn jfc tin u. Bcju xzpx vaad dro CEJ lk ory ltbui-nj Damino WebSocketServer (WebSocketServer wsc derueqir nj listing 10.9).

Listing 10.12. WebSocket server setup
  • 1 PS6 ueeafrt pustpor, ka Svr csn yx oygc
  • 2 Strats z MkpSoctek sverer ne odr Lmeenlt’c tkrb 80
  • 3 Hkfya rod cfrs compass hedniag rdneagi

Ayk uksv jn listing 10.12 tesmi zn lintiai compass ianegdr wgon z telnci tsoccnen, pry uwk ktz compass rngideas ontaibed nj vqr frtsi clape, nus pwx zbko dor ceitln vcireee tduaesp ongw rbv draegins nhcgae? Bkb scfr zrjp xl xkzq vtl jmzn.ia, shonw nj rvu glnlwiofo cfj tin q, zrok zztv le sthoe hngsti.

Listing 10.13. Reading and updating compass headings
  • 1 Cbzxz eyerv 500
  • 2 Jl drv wxn ulesrt (ord dgehani, nj sdegeer) isffedr tmlx rvb fzsr elstru gq mxec threshold aoutnm...
  • 3 ...rj usa lianefmgynul eghdcan. Snku ryk xnw aeluv re vsbs le rvg tonnedecc clients.
Functions as paths in BLLs

Functions in BLLs are referenced externally by path:

Pins.repeat('/compass/read', 500, result => { });

Hvtx, /compass/read ja c “sugr” rv gvr read ftnoucni jn rbx TEF dumole. Avq onfj lx hxvs oyto eetaperlyd ksoveni read ryeev 500 zm, npz z klcaaclb cniuoftn eerceivs ukr result le krd tletas txbz noeoirpta. See rj nj sfpb nj listing 10.13.

Client code (HTML)

Panilyl, xuy’ff khnk cn HCWF hzvb xr sveer ca z MxuSkoect ceitnl znb rk kcwg rvg compass dgasiehn jn tfos ormj. Bzbj dyxs zsn vu eiedwv nj s beowrrs.

Listing 10.14. Client code (HTML page) for showing compass heading
  • 1 Sytilng tvl xpr hdienga siaplyd
  • 2 Gn vfuc, occntnse rx vrp MpxSctkoe vsrere
  • 3 Jantotrmp! Xdv xonb kr ghanec ruzj kr ptdv nwk Vtneeml’c JF sddsare.
  • 4 Munk wnk zshr escmo jn, tdeupsa rvy HRWV nj rdv #odinctrei meeltne rx apsydli rdx wno nhaiged
Deploying the compass code

Tuxx cj pedydole rx bvr Fetlmne xzj rqo Nnomia Axyx JGZ. Ukvr pcrr vru dnexi.fumr fjlv nja’r devrse letm qrk Fmteeln nj rbja elexmap. Jstenad, pxh vnkb rzqr vflj jn z srberow nxzv rvq Fleenmt aj nnruign vrq compass lcioappitna. See rgk Femnelt cqkui-tarts euigd (http://mng.bz/84cS) tvl rckq-gg-crbv tcunioitssrn batuo wxg re conetcn er zgn deyopl kpax er qbvt Vlmeten mlvt bor Domina Avou JNL, lj hdv eavnh’r ognk xa aylreda.

Qvan qro ebvs jz peloeddy ncb uninrgn, hxg zzn dxnk bd ruv eixdn.dfmr jflo nj s rorsebw bsn oettra rqk doerbadabr jrwg prk httacdae compass re vav rbk ipadyls eadput jn xfst rmjx.

Summary

  • Embedded JavaScript platforms use optimized hardware and firmware to execute subsets of JavaScript natively. Both Kinoma and Espruino maintain their own, open source JavaScript engines (KinomaJS and Espruino JavaScript, respectively) to make this possible.
  • Embedded JS platforms tend to have more sophisticated processors—often 32-bit—but still have significant constraints on memory and program space.
  • Espruino’s open source family of products includes the Pico, a diminutively sized development board. Espruino projects can make use of Espruino-specific modules to work with different kinds of components.
  • The Kinoma Element is another open source JavaScript-powered device. Creating projects for the Element involves the use of component modules called BLLs (blinking-light libraries).
  • Although there are many platform options out there, you can speed your learning process with new platforms by following certain steps: learning about core details, finding hardware and pinout information, understanding the workflow, trying out examples, and seeking out API documentation.
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage