forked from Marzogh/SPIMemory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPIFlash.cpp
More file actions
1928 lines (1718 loc) · 60.3 KB
/
SPIFlash.cpp
File metadata and controls
1928 lines (1718 loc) · 60.3 KB
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Arduino SPIFlash Library v.2.5.0
* Copyright (C) 2015 by Prajwal Bhattaram
* Modified by Prajwal Bhattaram - 14/11/2016
*
* This file is part of the Arduino SPIFlash Library. This library is for
* Winbond NOR flash memory modules. In its current form it enables reading
* and writing individual data variables, structs and arrays from and to various locations;
* reading and writing pages; continuous read functions; sector, block and chip erase;
* suspending and resuming programming/erase and powering down for low power operation.
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License v3.0
* along with the Arduino SPIFlash Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "SPIFlash.h"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Uncomment the code below to run a diagnostic if your flash //
// does not respond //
// //
// Error codes will be generated and returned on functions //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//#define RUNDIAGNOSTIC //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Uncomment the code below to increase the speed of the library //
// by disabling _notPrevWritten() //
// //
// Make sure the sectors being written to have been erased beforehand //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//#define HIGHSPEED //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Constructor
#if defined (ARDUINO_ARCH_AVR)
SPIFlash::SPIFlash(uint8_t cs, bool overflow) {
csPin = cs;
#ifndef __AVR_ATtiny85__
cs_port = portOutputRegister(digitalPinToPort(csPin));
#endif
cs_mask = digitalPinToBitMask(csPin);
pageOverflow = overflow;
pinMode(csPin, OUTPUT);
}
#elif defined (ARDUINO_ARCH_ESP8266) || defined (ARDUINO_ARCH_SAMD) || defined (ARDUINO_ARCH_SAM)
SPIFlash::SPIFlash(uint8_t cs, bool overflow) {
csPin = cs;
pageOverflow = overflow;
pinMode(csPin, OUTPUT);
}
#endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Private functions used by read, write and erase operations //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Double checks all parameters before calling a read or write. Comes in two variants
//Variant A: Takes address and returns the address if true, else returns false. Throws an error if there is a problem.
bool SPIFlash::_prep(uint8_t opcode, uint32_t address, uint32_t size) {
switch (opcode) {
case PAGEPROG:
if (!_addressCheck(address, size)) {
return false;
}
if(!_notBusy() || !_writeEnable()){
return false;
}
#ifndef HIGHSPEED
if(!_notPrevWritten(address, size)) {
return false;
}
#endif
return true;
break;
default:
if (!_addressCheck(address, size)) {
return false;
}
if (!_notBusy()){
return false;
}
return true;
break;
}
}
//Variant B: Take the opcode, page number, offset and size of data block as arguments
bool SPIFlash::_prep(uint8_t opcode, uint32_t page_number, uint8_t offset, uint32_t size) {
uint32_t address = _getAddress(page_number, offset);
return _prep(opcode, address, size);
}
bool SPIFlash::_transferAddress(void) {
_nextByte(_currentAddress >> 16);
_nextByte(_currentAddress >> 8);
_nextByte(_currentAddress);
}
bool SPIFlash::_startSPIBus(void) {
#ifndef SPI_HAS_TRANSACTION
noInterrupts();
#endif
//save current SPI settings
#if defined (ARDUINO_ARCH_AVR)
_SPCR = SPCR;
_SPSR = SPSR;
#endif
#if defined (ARDUINO_ARCH_SAM)
_dueSPIInit(DUE_SPI_CLK);
#else
#ifdef SPI_HAS_TRANSACTION
SPI.beginTransaction(_settings);
#else
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
#endif
#endif
SPIBusState = true;
}
//Initiates SPI operation - but data is not transferred yet. Always call _prep() before this function (especially when it involves writing or reading to/from an address)
bool SPIFlash::_beginSPI(uint8_t opcode) {
if (!SPIBusState) {
//Serial.println("Starting SPI Bus");
_startSPIBus();
}
CHIP_SELECT
switch (opcode) {
case FASTREAD:
_nextByte(opcode);
_nextByte(DUMMYBYTE);
_transferAddress();
break;
case READDATA:
_nextByte(opcode);
_transferAddress();
break;
case PAGEPROG:
_nextByte(opcode);
_transferAddress();
break;
default:
_nextByte(opcode);
break;
}
return true;
}
//SPI data lines are left open until _endSPI() is called
//Reads/Writes next byte. Call 'n' times to read/write 'n' number of bytes. Should be called after _beginSPI()
uint8_t SPIFlash::_nextByte(uint8_t data) {
#if defined (ARDUINO_ARCH_SAM)
return _dueSPITransfer(data);
#else
return xfer(data);
#endif
}
//Reads/Writes next int. Call 'n' times to read/write 'n' number of bytes. Should be called after _beginSPI()
uint16_t SPIFlash::_nextInt(uint16_t data) {
//return xfer16(data);
SPI.transfer16(data);
}
//Reads/Writes next data buffer. Call 'n' times to read/write 'n' number of bytes. Should be called after _beginSPI()
void SPIFlash::_nextBuf(uint8_t opcode, uint8_t *data_buffer, uint32_t size) {
uint8_t *_dataAddr = &(*data_buffer);
switch (opcode) {
case READDATA:
#if defined (ARDUINO_ARCH_SAM)
_dueSPIRecByte(&(*data_buffer), size);
#elif defined (ARDUINO_ARCH_AVR)
SPI.transfer(&data_buffer[0], size);
#else
for (uint16_t i = 0; i < size; i++) {
*_dataAddr = xfer(NULLBYTE);
_dataAddr++;
}
#endif
break;
case PAGEPROG:
#if defined (ARDUINO_ARCH_SAM)
_dueSPISendByte(&(*data_buffer), size);
#elif defined (ARDUINO_ARCH_AVR)
SPI.transfer(&(*data_buffer), size);
#else
for (uint16_t i = 0; i < size; i++) {
xfer(*_dataAddr);
_dataAddr++;
}
#endif
break;
}
}
//Stops all operations. Should be called after all the required data is read/written from repeated _nextByte() calls
void SPIFlash::_endSPI(void) {
CHIP_DESELECT
#ifdef SPI_HAS_TRANSACTION
SPI.endTransaction();
#else
interrupts();
#endif
#if defined (ARDUINO_ARCH_AVR)
SPCR = _SPCR;
SPSR = _SPSR;
#endif
SPIBusState = false;
}
// Checks if status register 1 can be accessed - used during powerdown and power up and for debugging
uint8_t SPIFlash::_readStat1(void) {
_beginSPI(READSTAT1);
uint8_t stat1 = _nextByte();
//_endSPI();
CHIP_DESELECT
return stat1;
}
// Checks if status register 2 can be accessed, if yes, reads and returns it
uint8_t SPIFlash::_readStat2(void) {
_beginSPI(READSTAT2);
uint8_t stat2 = _nextByte();
_endSPI();
return stat2;
}
// Checks the erase/program suspend flag before enabling/disabling a program/erase suspend operation
bool SPIFlash::_noSuspend(void) {
if(_readStat2() & SUS) {
errorcode = NOSUSPEND;
return false;
}
return true;
}
// Polls the status register 1 until busy flag is cleared or timeout
bool SPIFlash::_notBusy(uint32_t timeout) {
uint32_t startTime = millis();
do {
state = _readStat1();
if((millis()-startTime) > timeout){
errorcode = CHIPBUSY;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
} while(state & BUSY);
return true;
}
//Enables writing to chip by setting the WRITEENABLE bit
bool SPIFlash::_writeEnable(uint32_t timeout) {
uint32_t startTime = millis();
if (!(state & WRTEN)) {
do {
_beginSPI(WRITEENABLE);
//_endSPI();
CHIP_DESELECT
state = _readStat1();
if((millis()-startTime) > timeout) {
errorcode = CANTENWRITE;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
} while (!(state & WRTEN));
}
return true;
}
//Disables writing to chip by setting the Write Enable Latch (WEL) bit in the Status Register to 0
//_writeDisable() is not required under the following conditions because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, Block Erase, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
bool SPIFlash::_writeDisable(void) {
_beginSPI(WRITEDISABLE);
_endSPI();
return true;
}
//Gets address from page number and offset. Takes two arguments:
// 1. page_number --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
uint32_t SPIFlash::_getAddress(uint16_t page_number, uint8_t offset) {
uint32_t address = page_number;
return ((address << 8) + offset);
}
//Checks the device ID to establish storage parameters
bool SPIFlash::_getManId(uint8_t *b1, uint8_t *b2) {
if(!_notBusy())
return false;
_beginSPI(MANID);
_nextByte();
_nextByte();
_nextByte();
*b1 = _nextByte();
*b2 = _nextByte();
_endSPI();
return true;
}
//Checks for presence of chip by requesting JEDEC ID
bool SPIFlash::_getJedecId(uint8_t *b1, uint8_t *b2, uint8_t *b3) {
if(!_notBusy())
return false;
_beginSPI(JEDECID);
*b1 = _nextByte(NULLBYTE); // manufacturer id
*b2 = _nextByte(NULLBYTE); // manufacturer id
*b3 = _nextByte(NULLBYTE); // capacity
_endSPI();
return true;
}
//Identifies the chip
bool SPIFlash::_chipID(void) {
//Get Manfucturer/Device ID so the library can identify the chip
uint8_t manID, capID, devID ;
//_getManId(&manID, &devID);
_getJedecId(&manID, &capID, &devID);
//Serial.println(manID, HEX);
//Serial.println(capID, HEX);
//Serial.println(devID, HEX);
if (manID != WINBOND_MANID && manID != MICROCHIP_MANID){ //If the chip is not a Winbond Chip
errorcode = UNKNOWNCHIP; //Error code for unidentified chip
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
while(1);
}
//Check flash memory type and identify capacity
uint8_t i;
//capacity & chip name
for (i = 0; i < sizeof(devType); i++)
{
if (devID == devType[i]) {
capacity = memSize[i];
name = chipName[i];
_eraseTime = eraseTime[i];
//Serial.println(devID, HEX);
//Serial.println(capacity);
//Serial.println(name);
}
}
if (capacity == 0) {
errorcode = UNKNOWNCAP; //Error code for unidentified capacity
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
while(1);
}
maxPage = capacity/PAGESIZE;
/*#ifdef RUNDIAGNOSTIC
char buffer[64];
sprintf(buffer, "Manufacturer ID: %02xh\nMemory Type: %02xh\nCapacity: %lu\nmaxPage: %d", manID, devID, capacity, maxPage);
Serial.println(buffer);
#endif*/
return true;
}
//Checks to see if pageOverflow is permitted and assists with determining next address to read/write.
//Sets the global address variable
bool SPIFlash::_addressCheck(uint32_t address, uint32_t size) {
if (capacity == 0) {
errorcode = CALLBEGIN;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
}
for (uint32_t i = 0; i < size; i++) {
if (address + i >= maxAddress) {
if (!pageOverflow) {
errorcode = OUTOFBOUNDS;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false; // At end of memory - (!pageOverflow)
}
else {
_currentAddress = 0x00;
return true; // At end of memory - (pageOverflow)
}
}
}
_currentAddress = address;
return true; // Not at end of memory if (address < capacity)
}
bool SPIFlash::_notPrevWritten(uint32_t address, uint32_t size) {
//_prep(READDATA, address, size);
_beginSPI(READDATA);
for (uint16_t i = 0; i < size; i++) {
if (_nextByte() != 0xFF) {
_endSPI();
return false;
}
}
//_endSPI();
CHIP_DESELECT
return true;
}
#ifdef RUNDIAGNOSTIC
//Troubleshooting function. Called when #ifdef RUNDIAGNOSTIC is uncommented at the top of this file.
void SPIFlash::_troubleshoot(void) {
switch (errorcode) {
case SUCCESS:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(SUCCESS, HEX);
#else
Serial.println("Action completed successfully");
#endif
break;
case CALLBEGIN:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(CALLBEGIN, HEX);
#else
Serial.println("*constructor_of_choice*.begin() was not called in void setup()");
#endif
break;
case UNKNOWNCHIP:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(UNKNOWNCHIP, HEX);
#else
Serial.println("Unable to identify chip. Are you sure this is a Winbond Flash chip");
Serial.println("Please raise an issue at http://www.github.com/Marzogh/SPIFlash/issues with your chip type and I will try to add support to your chip");
#endif
break;
case UNKNOWNCAP:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(UNKNOWNCAP, HEX);
#else
Serial.println("Unable to identify capacity.");
Serial.println("Please raise an issue at http://www.github.com/Marzogh/SPIFlash/issues with your chip type and I will work on adding support to your chip");
#endif
break;
case CHIPBUSY:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(CHIPBUSY, HEX);
#else
Serial.println("Chip is busy.");
Serial.println("Make sure all pins have been connected properly");
Serial.print("If it still doesn't work, ");
Serial.println("please raise an issue at http://www.github.com/Marzogh/SPIFlash/issues with the details of what your were doing when this error occurred");
#endif
break;
case OUTOFBOUNDS:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(OUTOFBOUNDS, HEX);
#else
Serial.println("Page overflow has been disabled and the address called exceeds the memory");
#endif
break;
case CANTENWRITE:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(CANTENWRITE, HEX);
#else
Serial.println("Unable to Enable Writing to chip.");
Serial.println("Please make sure the HOLD & WRITEPROTECT pins are connected properly to VCC & GND respectively");
Serial.print("If you are still facing issues, ");
Serial.println("please raise an issue at http://www.github.com/Marzogh/SPIFlash/issues with the details of what your were doing when this error occurred");
#endif
break;
case PREVWRITTEN:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(PREVWRITTEN, HEX);
#else
Serial.println("This sector already contains data.");
Serial.println("Please make sure the sectors being written to are erased.");
Serial.print("If you are still facing issues, ");
Serial.println("please raise an issue at http://www.github.com/Marzogh/SPIFlash/issues with the details of what your were doing when this error occurred");
#endif
break;
case LOWRAM:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(LOWRAM, HEX);
#else
Serial.println("You are running low on SRAM. Please optimise your program for better RAM usage");
#if defined (ARDUINO_ARCH_SAM)
Serial.print("Current Free SRAM: ");
Serial.println(_dueFreeRAM());
#endif
Serial.print("If you are still facing issues, ");
Serial.println("please raise an issue at http://www.github.com/Marzogh/SPIFlash/issues with the details of what your were doing when this error occurred");
#endif
break;
case NOSUSPEND:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(NOSUSPEND, HEX);
#else
Serial.println("Unable to suspend operation.");
Serial.print("If you are unable to resolve this problem, ");
Serial.println("please raise an issue at http://www.github.com/Marzogh/SPIFlash/issues with the details of what your were doing when this error occurred");
#endif
break;
default:
#if defined (ARDUINO_ARCH_AVR) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x");
Serial.println(UNKNOWNERROR, HEX);
#else
Serial.println("Unknown error");
Serial.println("Please raise an issue at http://www.github.com/Marzogh/SPIFlash/issues with the details of what your were doing when this error occurred");
#endif
break;
}
}
#endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Public functions used for read, write and erase operations //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Identifies chip and establishes parameters
void SPIFlash::begin(void) {
#if defined (ARDUINO_ARCH_SAM)
_dueSPIBegin();
#else
SPI.begin();
#endif
#ifdef SPI_HAS_TRANSACTION
//Define the settings to be used by the SPI bus
_settings = SPISettings(SPI_CLK, MSBFIRST, SPI_MODE0);
#endif
_chipID();
}
//Allows the setting of a custom clock speed for the SPI bus to communicate with the chip.
//Only works if the SPI library in use supports SPI Transactions
#ifdef SPI_HAS_TRANSACTION
void SPIFlash::setClock(uint32_t clockSpeed) {
_settings = SPISettings(clockSpeed, MSBFIRST, SPI_MODE0);
}
#endif
uint8_t SPIFlash::error(void) {
return errorcode;
}
//Returns capacity of chip
uint32_t SPIFlash::getCapacity(void) {
return capacity;
}
//Returns maximum number of pages
uint32_t SPIFlash::getMaxPage(void) {
return maxPage;
}
//Returns identifying name of the chip
uint16_t SPIFlash::getChipName(void) {
return name;
}
//Returns the library version as a string
bool SPIFlash::libver(uint8_t *b1, uint8_t *b2, uint8_t *b3) {
*b1 = LIBVER;
*b2 = LIBSUBVER;
*b3 = BUGFIXVER;
return true;
}
//Checks for and initiates the chip by requesting the Manufacturer ID which is returned as a 16 bit int
uint16_t SPIFlash::getManID(void) {
uint8_t b1, b2;
_getManId(&b1, &b2);
uint32_t id = b1;
id = (id << 8)|(b2 << 0);
return id;
}
//Checks for and initiates the chip by requesting JEDEC ID which is returned as a 32 bit int
uint32_t SPIFlash::getJEDECID(void) {
uint8_t b1, b2, b3;
_getJedecId(&b1, &b2, &b3);
uint32_t id = b1;
id = (id << 8)|(b2 << 0);
id = (id << 8)|(b3 << 0);
return id;
}
//Gets the next available address for use. Has two variants:
// A. Takes the size of the data as an argument and returns a 32-bit address
// B. Takes a three variables, the size of the data and two other variables to return a page number value & an offset into.
// All addresses in the in the sketch must be obtained via this function or not at all.
// Variant A
uint32_t SPIFlash::getAddress(uint16_t size) {
if (!_addressCheck(currentAddress, size)){
errorcode = OUTOFBOUNDS;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
else {
uint32_t address = currentAddress;
/*Serial.print("Current Address: ");
Serial.println(currentAddress);*/
currentAddress+=size;
return address;
}
}
// Variant B
bool SPIFlash::getAddress(uint16_t size, uint16_t &page_number, uint8_t &offset) {
uint32_t address = getAddress(size);
offset = (address >> 0);
page_number = (address >> 8);
return true;
}
//Function for returning the size of the string (only to be used for the getAddress() function)
uint16_t SPIFlash::sizeofStr(String &inputStr) {
//uint16_t inStrLen = inputStr.length() + 1;
uint16_t size;
//inputStr.toCharArray(inputChar, inStrLen);
//size=(sizeof(char)*inStrLen);
size = (sizeof(char)*(inputStr.length()+1));
size+=sizeof(inputStr.length()+1/*inStrLen*/);
return size;
}
// Reads a byte of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint8_t SPIFlash::readByte(uint32_t address, bool fastRead) {
uint8_t data;
if (!_prep(READDATA, address, sizeof(data))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
data = _nextByte();
_endSPI();
return data;
}
// Variant B
uint8_t SPIFlash::readByte(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readByte(address, fastRead);
}
// Reads a char of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int8_t SPIFlash::readChar(uint32_t address, bool fastRead) {
int8_t data;
if (!_prep(READDATA, address, sizeof(data))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
data = _nextByte();
_endSPI();
return data;
}
// Variant B
int8_t SPIFlash::readChar(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readChar(address, fastRead);
}
// Reads an array of bytes starting from a specific location in a page.// Has two variants:
// A. Takes three arguments
// 1. address --> Any address from 0 to maxAddress
// 2. data_buffer --> The array of bytes to be read from the flash memory - starting at the address indicated
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes four arguments
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data_buffer --> The array of bytes to be read from the flash memory - starting at the offset on the page indicated
// 4. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
bool SPIFlash::readByteArray(uint32_t address, uint8_t *data_buffer, uint16_t bufferSize, bool fastRead) {
if (!_prep(READDATA, address, bufferSize)) {
return false;
}
if(fastRead) {
_beginSPI(FASTREAD);
}
else {
_beginSPI(READDATA);
}
_nextBuf(READDATA, &(*data_buffer), bufferSize);
_endSPI();
return true;
}
// Variant B
bool SPIFlash::readByteArray(uint16_t page_number, uint8_t offset, uint8_t *data_buffer, uint16_t bufferSize, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readByteArray(address, data_buffer, bufferSize, fastRead);
}
// Reads an array of chars starting from a specific location in a page.// Has two variants:
// A. Takes three arguments
// 1. address --> Any address from 0 to maxAddress
// 2. data_buffer --> The array of bytes to be read from the flash memory - starting at the address indicated
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes four arguments
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data_buffer --> The array of bytes to be read from the flash memory - starting at the offset on the page indicated
// 4. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
bool SPIFlash::readCharArray(uint32_t address, char *data_buffer, uint16_t bufferSize, bool fastRead) {
if (!_prep(READDATA, address, bufferSize)) {
return false;
}
if(fastRead) {
_beginSPI(FASTREAD);
}
else {
_beginSPI(READDATA);
}
_nextBuf(READDATA, (uint8_t*) &(*data_buffer), bufferSize);
_endSPI();
return true;
}
// Variant B
bool SPIFlash::readCharArray(uint16_t page_number, uint8_t offset, char *data_buffer, uint16_t bufferSize, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readCharArray(address, data_buffer, bufferSize, fastRead);
}
// Reads an unsigned int of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint16_t SPIFlash::readWord(uint32_t address, bool fastRead) {
const uint8_t size = sizeof(uint16_t);
union
{
uint8_t b[size];
uint16_t I;
} data;
if (!_prep(READDATA, address, size)) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.I;
}
// Variant B
uint16_t SPIFlash::readWord(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readWord(address, fastRead);
}
// Reads a signed int of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int16_t SPIFlash::readShort(uint32_t address, bool fastRead) {
const uint8_t size = sizeof(int16_t);
union
{
byte b[size];
int16_t s;
} data;
if (!_prep(READDATA, address, size)) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.s;
}
// Variant B
int16_t SPIFlash::readShort(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readShort(address, fastRead);
}
// Reads an unsigned long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint32_t SPIFlash::readULong(uint32_t address, bool fastRead) {
const uint8_t size = (sizeof(uint32_t));
union
{
uint8_t b[size];
uint32_t l;
} data;
if (!_prep(READDATA, address, size)) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.l;
}
// Variant B
uint32_t SPIFlash::readULong(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readULong(address, fastRead);
}
// Reads a signed long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int32_t SPIFlash::readLong(uint32_t address, bool fastRead) {
const uint8_t size = (sizeof(int32_t));
union
{
byte b[size];
int32_t l;
} data;
if (!_prep(READDATA, address, size)) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
_nextBuf(READDATA, &data.b[0], size);
_endSPI();
return data.l;
}
// Variant B
int32_t SPIFlash::readLong(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readLong(address, fastRead);
}
// Reads a signed long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true