-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjswrap_spi_i2c.c
689 lines (623 loc) · 22.4 KB
/
jswrap_spi_i2c.c
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
/*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <[email protected]>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* This file is designed to be parsed during the build process
*
* JavaScript SPI and I2C Functions
* ----------------------------------------------------------------------------
*/
#include "jswrap_spi_i2c.h"
#include "jsdevices.h"
#include "jsinteractive.h"
#include "jswrap_arraybuffer.h"
/*JSON{
"type" : "class",
"class" : "SPI"
}
This class allows use of the built-in SPI ports. Currently it is SPI master only.
*/
/*JSON{
"type" : "object",
"name" : "SPI1",
"instanceof" : "SPI",
"#if" : "SPIS>=1"
}
The first SPI port
*/
/*JSON{
"type" : "object",
"name" : "SPI2",
"instanceof" : "SPI",
"#if" : "SPIS>=2"
}
The second SPI port
*/
/*JSON{
"type" : "object",
"name" : "SPI3",
"instanceof" : "SPI",
"#if" : "SPIS>=3"
}
The third SPI port
*/
typedef int (*spi_sender)(int data, void *info);
int spi_sender_hardware(int data, void *info) {
IOEventFlags device = *(IOEventFlags*)info;
return jshSPISend(device, data);
}
int spi_sender_software(int data, void *info) {
/*if (data<0) return -1;
JshSPIInfo *inf = (JshSPIInfo*)info;
bool CPHA = (inf->spiMode & SPIF_CPHA)!=0;
bool CPOL = (inf->spiMode & SPIF_CPOL)!=0;
int result = 0;
int bit = inf->spiMSB ? 7 : 0;
int bitDir = inf->spiMSB ? -1 : 1;
int endBit = inf->spiMSB ? -1 : 8;
for (;bit!=endBit;bit+=bitDir) {
if (!CPHA) { // 'Normal' SPI, CPHA=0
if (inf->pinMOSI != NC)
jshPinSetValue(inf->pinMOSI, (data>>bit)&1 );
if (inf->pinSCK != NC)
jshPinSetValue(inf->pinSCK, CPOL ? 0 : 1 );
if (inf->pinMISO != NC)
result = (result<<1) | (jshPinGetValue(inf->pinMISO )?1:0);
if (inf->pinSCK != NC)
jshPinSetValue(inf->pinSCK, CPOL ? 1 : 0 );
} else { // CPHA=1
if (inf->pinSCK != NC)
jshPinSetValue(inf->pinSCK, CPOL ? 0 : 1 );
if (inf->pinMOSI != NC)
jshPinSetValue(inf->pinMOSI, (data>>bit)&1 );
if (inf->pinSCK != NC)
jshPinSetValue(inf->pinSCK, CPOL ? 1 : 0 );
if (inf->pinMISO != NC)
result = (result<<1) | (jshPinGetValue(inf->pinMISO )?1:0);
}
}
return result;
*/
return 0;
}
/*JSON{
"type" : "constructor",
"class" : "SPI",
"name" : "SPI",
"generate" : "jswrap_spi_constructor"
}
Create a software SPI port. This has limited functionality (no baud rate), but it can work on any pins.
*/
JsVar *jswrap_spi_constructor() {
return jsvNewWithFlags(JSV_OBJECT);
}
static void jswrap_spi_populate_info(JshSPIInfo *inf, JsVar *options) {
jshSPIInitInfo(inf);
if (jsvIsObject(options)) {
inf->pinSCK = jshGetPinFromVarAndUnLock(jsvObjectGetChild(options, "sck", 0));
inf->pinMISO = jshGetPinFromVarAndUnLock(jsvObjectGetChild(options, "miso", 0));
inf->pinMOSI = jshGetPinFromVarAndUnLock(jsvObjectGetChild(options, "mosi", 0));
JsVar *v;
v = jsvObjectGetChild(options, "baud", 0);
if (jsvIsNumeric(v))
inf->baudRate = (int)jsvGetInteger(v);
v = jsvObjectGetChild(options, "mode", 0);
if (jsvIsNumeric(v))
inf->spiMode = (int)jsvGetInteger(v);
v = jsvObjectGetChild(options, "bits", 0);
if (jsvIsNumeric(v))
inf->bits = (int)jsvGetInteger(v);
/*v = jsvObjectGetChild(options, "order", 0);
if (jsvIsString(v) && jsvIsStringEqual(v, "msb")) {
inf->spiMSB = true;
} else if (jsvIsString(v) && jsvIsStringEqual(v, "lsb")) {
inf->spiMSB = false;
} else if (!jsvIsUndefined(v))
jsWarn("SPI order should be 'msb' or 'lsb'");
*/
jsvUnLock(v);
}
}
/*JSON{
"type" : "method",
"class" : "SPI",
"name" : "setup",
"generate" : "jswrap_spi_setup",
"params" : [
["options","JsVar",["An optional structure containing extra information on initialising the SPI port","Please note that baud rate is set to the nearest that can be managed - which may be -+ 50%","```{sck:pin, miso:pin, mosi:pin, baud:integer=100000, mode:integer=0, order:'msb'/'lsb'='msb' }```","If sck,miso and mosi are left out, they will automatically be chosen. However if one or more is specified then the unspecified pins will not be set up.","You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `SPI` marker.","The SPI ```mode``` is between 0 and 3 - see http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase","On STM32F1-based parts, you cannot mix AF and non-AF pins (SPI pins are usually grouped on the chip - and you can't mix pins from two groups). Espruino will not warn you about this."]]
]
}
Set up this SPI port as an SPI Master.
*/
void jswrap_spi_setup(JsVar *parent, JsVar *options) {
IOEventFlags device = jsiGetDeviceFromClass(parent);
JshSPIInfo inf;
jswrap_spi_populate_info(&inf, options);
if (DEVICE_IS_SPI(device)) {
jshSPISetup(device, &inf);
} else if (device == EV_NONE) {
// software mode - at least configure pins properly
if (inf.pinSCK != NC)
jshPinSetState(inf.pinSCK, JSHPINSTATE_GPIO_OUT);
if (inf.pinMISO != NC)
jshPinSetState(inf.pinMISO, JSHPINSTATE_GPIO_IN);
if (inf.pinMOSI != NC)
jshPinSetState(inf.pinMOSI, JSHPINSTATE_GPIO_OUT);
} else return;
// Set up options, so we can initialise it on startup
if (options)
jsvUnLock(jsvSetNamedChild(parent, options, DEVICE_OPTIONS_NAME));
else
jsvRemoveNamedChild(parent, DEVICE_OPTIONS_NAME);
}
/*JSON{
"type" : "method",
"class" : "SPI",
"name" : "send",
"generate" : "jswrap_spi_send",
"params" : [
["data","JsVar","The data to send - either an integer, array, or string (which is the most efficient)"],
["nss_pin","pin","An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised."]
],
"return" : ["JsVar","The data that was returned"]
}
Send data down SPI, and return the result
Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.
*/
JsVar *jswrap_spi_send(JsVar *parent, JsVar *srcdata, Pin nss_pin) {
NOT_USED(parent);
IOEventFlags device = jsiGetDeviceFromClass(parent);
spi_sender spiSend;
void *spiSendData;
if (DEVICE_IS_SPI(device)) {
if (!jshIsDeviceInitialised(device)) {
JshSPIInfo inf;
jshSPIInitInfo(&inf);
jshSPISetup(device, &inf);
}
spiSend = spi_sender_hardware;
spiSendData = &device;
} else if (device == EV_NONE) {
JsVar *options = jsvObjectGetChild(parent, DEVICE_OPTIONS_NAME, 0);
JshSPIInfo inf;
jswrap_spi_populate_info(&inf, options);
jsvUnLock(options);
spiSend = spi_sender_software;
spiSendData = &inf;
} else return 0;
JsVar *dst = 0;
// assert NSS
if (nss_pin!=NC) jshPinOutput(nss_pin, false);
// send data
if (jsvIsNumeric(srcdata)) {
int r = spiSend((unsigned char)jsvGetInteger(srcdata), spiSendData);
if (r<0) r = spiSend(-1, spiSendData);
dst = jsvNewFromInteger(r); // retrieve the byte (no send!)
} else if (jsvIsArray(srcdata)) {
dst = jsvNewWithFlags(JSV_ARRAY);
if (!dst) return 0;
JsvObjectIterator it;
jsvObjectIteratorNew(&it, srcdata);
int incount = 0, outcount = 0;
while (jsvObjectIteratorHasValue(&it) && !jspIsInterrupted()) {
unsigned char in = (unsigned char)jsvGetIntegerAndUnLock(jsvObjectIteratorGetValue(&it));
incount++;
int out = spiSend(in, spiSendData); // this returns -1 only if no data (so if -1 gets in an array it is an error!)
if (out>=0) {
outcount++;
JsVar *outVar = jsvNewFromInteger(out);
jsvArrayPushAndUnLock(dst, outVar);
}
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
// finally add the remaining bytes (no send!)
while (outcount < incount && !jspIsInterrupted()) {
outcount++;
int out = spiSend(-1, spiSendData);
JsVar *outVar = jsvNewFromInteger(out);
jsvArrayPushAndUnLock(dst, outVar);
}
} else if (jsvIsString(srcdata)) {
dst = jsvNewFromEmptyString();
JsvStringIterator it;
jsvStringIteratorNew(&it, srcdata, 0);
int incount = 0, outcount = 0;
while (jsvStringIteratorHasChar(&it) && !jspIsInterrupted()) {
unsigned char in = (unsigned char)jsvStringIteratorGetChar(&it);
incount++;
int out = spiSend(in, spiSendData);
if (out>=0) {
outcount++;
char outc = (char)out;
jsvAppendStringBuf(dst, (char*)&outc, 1);
}
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
// finally add the remaining bytes (no send!)
while (outcount < incount && !jspIsInterrupted()) {
outcount++;
unsigned char out = (unsigned char)spiSend(-1, spiSendData);
jsvAppendStringBuf(dst, (char*)&out, 1);
}
} else if (jsvIsIterable(srcdata)) {
dst = jsvNewTypedArray(ARRAYBUFFERVIEW_UINT8, jsvGetLength(srcdata));
if (!dst) return 0;
JsvIterator it;
JsvArrayBufferIterator dstit;
jsvIteratorNew(&it, srcdata);
jsvArrayBufferIteratorNew(&dstit, dst, 0);
int incount = 0, outcount = 0;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
unsigned char in = (unsigned char)jsvIteratorGetIntegerValue(&it);
incount++;
int out = spiSend(in, spiSendData);
if (out>=0) {
outcount++;
jsvArrayBufferIteratorSetIntegerValue(&dstit, (char)out);
jsvArrayBufferIteratorNext(&dstit);
}
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
// finally add the remaining bytes (no send!)
while (outcount < incount && !jspIsInterrupted()) {
outcount++;
jsvArrayBufferIteratorSetIntegerValue(&dstit, (unsigned char)spiSend(-1, spiSendData));
jsvArrayBufferIteratorNext(&dstit);
}
jsvArrayBufferIteratorFree(&dstit);
} else {
jsExceptionHere(JSET_ERROR, "Variable type %t not suited to transmit operation", srcdata);
dst = 0;
}
// de-assert NSS
if (nss_pin!=NC) jshPinOutput(nss_pin, true);
return dst;
}
/*JSON{
"type" : "method",
"class" : "SPI",
"name" : "write",
"generate" : "jswrap_spi_write",
"params" : [
["data","JsVarArray",["One or more items to write. May be ints, strings, arrays, or objects of the form `{data: ..., count:#}`.","If the last argument is a pin, it is taken to be the NSS pin"]]
]
}
Write a character or array of characters to SPI - without reading the result back
*/
void jswrap_spi_write(JsVar *parent, JsVar *args) {
NOT_USED(parent);
IOEventFlags device = jsiGetDeviceFromClass(parent);
spi_sender spiSend;
void *spiSendData;
if (DEVICE_IS_SPI(device)) {
if (!jshIsDeviceInitialised(device)) {
JshSPIInfo inf;
jshSPIInitInfo(&inf);
jshSPISetup(device, &inf);
}
spiSend = spi_sender_hardware;
spiSendData = &device;
} else if (device == EV_NONE) {
JsVar *options = jsvObjectGetChild(parent, DEVICE_OPTIONS_NAME, 0);
JshSPIInfo inf;
jswrap_spi_populate_info(&inf, options);
jsvUnLock(options);
spiSend = spi_sender_software;
spiSendData = &inf;
} else return;
Pin nss_pin = NC;
// If the last value is a pin, use it as the NSS pin
JsVarInt len = jsvGetArrayLength(args);
if (len>0) {
JsVar *last = jsvGetArrayItem(args, len-1); // look at the last value
if (jsvIsPin(last)) {
nss_pin = jshGetPinFromVar(last);
jsvUnLock(jsvArrayPop(args));
}
jsvUnLock(last);
}
// Wait until SPI send is finished, and flush data
if (DEVICE_IS_SPI(device))
jshSPIWait(device);
// assert NSS
if (nss_pin!=NC) jshPinOutput(nss_pin, false);
// Write data
jsvIterateCallback(args, (void (*)(int, void *))spiSend, spiSendData);
// de-assert NSS
if (nss_pin!=NC) jshPinOutput(nss_pin, true);
}
// used by jswrap_spi_send4bit
void spi_send4bit(IOEventFlags device, unsigned char data, int bit0, int bit1) {
unsigned char lookup[] = {
(unsigned char)((bit0<<4) | bit0),
(unsigned char)((bit0<<4) | bit1),
(unsigned char)((bit1<<4) | bit0),
(unsigned char)((bit1<<4) | bit1),
};
// Send each bit as 4 bits, MSB first
/*jshSPISend(device, lookup[(data>>6)&3]);
jshSPISend(device, lookup[(data>>4)&3]);
jshSPISend(device, lookup[(data>>2)&3]);
jshSPISend(device, lookup[(data )&3]);*/
jshSPISend16(device, (lookup[(data>>6)&3]<<8) | lookup[(data>>4)&3]);
jshSPISend16(device, (lookup[(data>>2)&3]<<8) | lookup[(data )&3]);
}
// used by jswrap_spi_send8bit
void spi_send8bit(IOEventFlags device, unsigned char data, int bit0, int bit1) {
// Send each bit as 8 bits, MSB first
/*int i;
for (i=7;i>=0;i--)
jshSPISend(device, (unsigned char)(((data>>i)&1) ? bit1 : bit0));*/
jshSPISend(device, ((((data>>7)&1) ? bit1 : bit0)<<8) | (((data>>6)&1) ? bit1 : bit0));
jshSPISend(device, ((((data>>5)&1) ? bit1 : bit0)<<8) | (((data>>4)&1) ? bit1 : bit0));
jshSPISend(device, ((((data>>3)&1) ? bit1 : bit0)<<8) | (((data>>2)&1) ? bit1 : bit0));
jshSPISend(device, ((((data>>1)&1) ? bit1 : bit0)<<8) | (((data>>0)&1) ? bit1 : bit0));
}
/*JSON{
"type" : "method",
"class" : "SPI",
"name" : "send4bit",
"generate" : "jswrap_spi_send4bit",
"params" : [
["data","JsVar","The data to send - either an integer, array, or string"],
["bit0","int32","The 4 bits to send for a 0 (MSB first)"],
["bit1","int32","The 4 bits to send for a 1 (MSB first)"],
["nss_pin","pin","An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised."]
]
}
Send data down SPI, using 4 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols
Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.
*/
void jswrap_spi_send4bit(JsVar *parent, JsVar *srcdata, int bit0, int bit1, Pin nss_pin) {
NOT_USED(parent);
IOEventFlags device = jsiGetDeviceFromClass(parent);
if (!DEVICE_IS_SPI(device)) {
jsExceptionHere(JSET_ERROR, "SPI.send4bit only works on hardware SPI");
return;
}
jshSPISet16(device, true); // 16 bit output
if (bit0==0 && bit1==0) {
bit0 = 0x01;
bit1 = 0x03;
}
bit0 = bit0 & 0x0F;
bit1 = bit1 & 0x0F;
if (!jshIsDeviceInitialised(device)) {
JshSPIInfo inf;
jshSPIInitInfo(&inf);
jshSPISetup(device, &inf);
}
// assert NSS
if (nss_pin!=NC) jshPinOutput(nss_pin, false);
// send data
if (jsvIsNumeric(srcdata)) {
spi_send4bit(device, (unsigned char)jsvGetInteger(srcdata), bit0, bit1);
} else if (jsvIsIterable(srcdata)) {
jshInterruptOff();
JsvIterator it;
jsvIteratorNew(&it, srcdata);
while (jsvIteratorHasElement(&it)) {
unsigned char in = (unsigned char)jsvIteratorGetIntegerValue(&it);
spi_send4bit(device, in, bit0, bit1);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
jshInterruptOn();
} else {
jsExceptionHere(JSET_ERROR, "Variable type %t not suited to transmit operation", srcdata);
}
// de-assert NSS
if (nss_pin!=NC) jshPinOutput(nss_pin, true);
jshSPISet16(device, false); // back to 8 bit
}
/*JSON{
"type" : "method",
"class" : "SPI",
"name" : "send8bit",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_spi_send8bit",
"params" : [
["data","JsVar","The data to send - either an integer, array, or string"],
["bit0","int32","The 8 bits to send for a 0 (MSB first)"],
["bit1","int32","The 8 bits to send for a 1 (MSB first)"],
["nss_pin","pin","An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised"]
]
}
Send data down SPI, using 8 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols
Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.
*/
void jswrap_spi_send8bit(JsVar *parent, JsVar *srcdata, int bit0, int bit1, Pin nss_pin) {
NOT_USED(parent);
IOEventFlags device = jsiGetDeviceFromClass(parent);
if (!DEVICE_IS_SPI(device)) {
jsExceptionHere(JSET_ERROR, "SPI.send8bit only works on hardware SPI");
return;
}
jshSPISet16(device, true); // 16 bit output
if (bit0==0 && bit1==0) {
bit0 = 0x03;
bit1 = 0x0F;
}
bit0 = bit0 & 0xFF;
bit1 = bit1 & 0xFF;
if (!jshIsDeviceInitialised(device)) {
JshSPIInfo inf;
jshSPIInitInfo(&inf);
jshSPISetup(device, &inf);
}
// assert NSS
if (nss_pin!=NC) jshPinOutput(nss_pin, false);
// send data
if (jsvIsNumeric(srcdata)) {
spi_send8bit(device, (unsigned char)jsvGetInteger(srcdata), bit0, bit1);
} else if (jsvIsIterable(srcdata)) {
jshInterruptOff();
JsvIterator it;
jsvIteratorNew(&it, srcdata);
while (jsvIteratorHasElement(&it)) {
unsigned char in = (unsigned char)jsvIteratorGetIntegerValue(&it);
spi_send8bit(device, in, bit0, bit1);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
jshInterruptOn();
} else {
jsExceptionHere(JSET_ERROR, "Variable type %t not suited to transmit operation", srcdata);
}
// de-assert NSS
if (nss_pin!=NC) jshPinOutput(nss_pin, true);
jshSPISet16(device, false); // back to 8 bit
}
/*JSON{
"type" : "class",
"class" : "I2C"
}
This class allows use of the built-in I2C ports. Currently it allows I2C Master mode only.
All addresses are in 7 bit format. If you have an 8 bit address then you need to shift it one bit to the right.
*/
/*JSON{
"type" : "object",
"name" : "I2C1",
"instanceof" : "I2C",
"#if" : "I2CS>=1"
}
The first I2C port
*/
/*JSON{
"type" : "object",
"name" : "I2C2",
"instanceof" : "I2C",
"#if" : "I2CS>=2"
}
The second I2C port
*/
/*JSON{
"type" : "object",
"name" : "I2C3",
"instanceof" : "I2C",
"#if" : "I2CS>=3"
}
The third I2C port
*/
/*JSON{
"type" : "method",
"class" : "I2C",
"name" : "setup",
"generate" : "jswrap_i2c_setup",
"params" : [
["options","JsVar",["An optional structure containing extra information on initialising the I2C port","```{scl:pin, sda:pin, bitrate:100000}```","You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `I2C` marker. Note that 400000kHz is the maximum bitrate for most parts."]]
]
}
Set up this I2C port
If not specified in options, the default pins are used (usually the lowest numbered pins on the lowest port that supports this peripheral)
*/
void jswrap_i2c_setup(JsVar *parent, JsVar *options) {
IOEventFlags device = jsiGetDeviceFromClass(parent);
if (!DEVICE_IS_I2C(device)) return;
JshI2CInfo inf;
jshI2CInitInfo(&inf);
if (jsvIsObject(options)) {
inf.pinSCL = jshGetPinFromVarAndUnLock(jsvObjectGetChild(options, "scl", 0));
inf.pinSDA = jshGetPinFromVarAndUnLock(jsvObjectGetChild(options, "sda", 0));
JsVar *v = jsvObjectGetChild(options, "bitrate", 0);
if (v)
inf.bitrate = jsvGetIntegerAndUnLock(v);
}
jshI2CSetup(device, &inf);
// Set up options, so we can initialise it on startup
if (options)
jsvUnLock(jsvSetNamedChild(parent, options, DEVICE_OPTIONS_NAME));
else
jsvRemoveNamedChild(parent, DEVICE_OPTIONS_NAME);
}
static NO_INLINE int i2c_get_address(JsVar *address, bool *sendStop) {
*sendStop = true;
if (jsvIsObject(address)) {
JsVar *stopVar = jsvObjectGetChild(address, "stop", 0);
if (stopVar) *sendStop = jsvGetBoolAndUnLock(stopVar);
return jsvGetIntegerAndUnLock(jsvObjectGetChild(address, "address", 0));
} else
return jsvGetInteger(address);
}
/*JSON{
"type" : "method",
"class" : "I2C",
"name" : "writeTo",
"generate" : "jswrap_i2c_writeTo",
"params" : [
["address","JsVar","The 7 bit address of the device to transmit to, or an object of the form `{address:12, stop:false}` to send this data without a STOP signal."],
["data","JsVarArray","One or more items to write. May be ints, strings, arrays, or objects of the form `{data: ..., count:#}`."]
]
}
Transmit to the slave device with the given address. This is like Arduino's beginTransmission, write, and endTransmission rolled up into one.
*/
typedef struct { unsigned char *buf; int idx; } JsI2CWriteCbData;
static void jswrap_i2c_writeToCb(int data, void *userData) {
JsI2CWriteCbData *cbData = (JsI2CWriteCbData*)userData;
cbData->buf[cbData->idx++] = (unsigned char)data;
}
void jswrap_i2c_writeTo(JsVar *parent, JsVar *addressVar, JsVar *args) {
IOEventFlags device = jsiGetDeviceFromClass(parent);
if (!DEVICE_IS_I2C(device)) return;
bool sendStop = true;
int address = i2c_get_address(addressVar, &sendStop);
size_t l = (size_t)jsvIterateCallbackCount(args);
if (l+256 > jsuGetFreeStack()) {
jsExceptionHere(JSET_ERROR, "Not enough free stack to send this amount of data");
return;
}
JsI2CWriteCbData cbData;
cbData.buf = (unsigned char *)alloca(l);
cbData.idx = 0;
jsvIterateCallback(args, jswrap_i2c_writeToCb, (void*)&cbData);
jshI2CWrite(device, (unsigned char)address, cbData.idx, cbData.buf, sendStop);
}
/*JSON{
"type" : "method",
"class" : "I2C",
"name" : "readFrom",
"generate" : "jswrap_i2c_readFrom",
"params" : [
["address","JsVar","The 7 bit address of the device to request bytes from, or an object of the form `{address:12, stop:false}` to send this data without a STOP signal."],
["quantity","int32","The number of bytes to request"]
],
"return" : ["JsVar","The data that was returned - as a Uint8Array"],
"return_object" : "Uint8Array"
}
Request bytes from the given slave device, and return them as a Uint8Array (packed array of bytes). This is like using Arduino Wire's requestFrom, available and read functions. Sends a STOP
*/
JsVar *jswrap_i2c_readFrom(JsVar *parent, JsVar *addressVar, int nBytes) {
IOEventFlags device = jsiGetDeviceFromClass(parent);
if (!DEVICE_IS_I2C(device)) return 0;
bool sendStop = true;
int address = i2c_get_address(addressVar, &sendStop);
if (nBytes<=0)
return 0;
if ((unsigned int)nBytes+256 > jsuGetFreeStack()) {
jsExceptionHere(JSET_ERROR, "Not enough free stack to receive this amount of data");
return 0;
}
unsigned char *buf = (unsigned char *)alloca((size_t)nBytes);
jshI2CRead(device, (unsigned char)address, nBytes, buf, sendStop);
JsVar *array = jsvNewTypedArray(ARRAYBUFFERVIEW_UINT8, nBytes);
if (array) {
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, array, 0);
unsigned int i;
for (i=0;i<(unsigned)nBytes;i++) {
jsvArrayBufferIteratorSetByteValue(&it, (char)buf[i]);
jsvArrayBufferIteratorNext(&it);
}
jsvArrayBufferIteratorFree(&it);
}
return array;
}