forked from capiman/lpc21isp
-
Notifications
You must be signed in to change notification settings - Fork 4
/
lpc21isp.c
2583 lines (2266 loc) · 96.5 KB
/
lpc21isp.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
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
/******************************************************************************
Project: Portable command line ISP for NXP LPC family
and Analog Devices ADUC70xx
Filename: lpc21isp.c
Compiler: Microsoft VC 6/7, Microsoft VS2008, Microsoft VS2010,
GCC Cygwin, GCC Linux, GCC ARM ELF
Author: Martin Maurer ([email protected])
Copyright: (c) Martin Maurer 2003-2014, All rights reserved
Portions Copyright (c) by Aeolus Development 2004 http://www.aeolusdevelopment.com
This file is part of lpc21isp.
lpc21isp is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
lpc21isp 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
and GNU General Public License along with lpc21isp.
If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(_WIN32)
#if !defined __BORLANDC__
#include "StdAfx.h" // Precompiled Header for WIN32
#endif
#endif // defined(_WIN32)
#include "lpc21isp.h" // if using propriatory serial port communication (customize attached lpc21isp.h)
#include "adprog.h"
#include "lpcprog.h"
#include "lpcterm.h"
/*
Change-History:
1.00 2004-01-08 Initial Version, tested for MSVC6/7 and GCC under Cygwin
1.01 2004-01-10 Porting to Linux (at least compiling must work)
1.02 2004-01-10 Implemented conversion intel hex format -> binary
1.03 2004-01-25 Preparation to upload to public website
1.04 2004-02-12 Merged in bugfixes by Soeren Gust
1.05 2004-03-14 Implement printing of error codes as text / strings
1.06 2004-03-09 Merged in bugfixes by Charles Manning:
The '?' sychronisation does not reliably respond to the first '?'.
I added some retries.
The LPC2106 sometimes responds to the '?' by echoing them back.
This sometimes causes an attempt to match "?Synchonized".
Added code to strip off any leading '?'s.
Timeouts were too long.
Change from RTS/CTS to no flow control.
Done because many/most people will use only 3-wire comms.
Added some progress tracing.
1.07 2004-03-14 Implement handling of control lines for easier booting
1.08 2004-04-01 Bugfix for upload problem
1.09 2004-04-03 Redesign of upload routine
Now always 180 byte blocks are uploaded, to prevent
small junks in uuencoding
1.10 2004-04-03 Clear buffers before sending commands to LPC21xx,
this prevents synchronizing errors when previously loaded
program does a lot of output, so FIFO of PC runs full
1.11 2004-04-03 Small optimization for controlling reset line
otherwise termonly starts LPC twice, free PC buffers
1.12 2004-04-04 Add switch to enable logging terminal output to lpc21isp.log
1.13 2004-05-19 Merged in improvement by Charles Manning:
Instead of exiting the wrong hex file size is corrected
1.14 2004-07-07 Merged in improvement by Alex Holden:
Remove little/big endian dependancy
1.15 2004-09-27 Temporary improvement by Cyril Holweck:
Removed test (data echoed = data transmited) on the main
data transfert, since this was the biggest failure
reason and is covered by checksome anyway.
Added COMPILE_FOR_LPC21, to have target dump it's own
memory to stdout.
1.16 2004-10-09 Merged in bugfix / improvement by Sinelnikov Evgeny
I found out that Linux and Windows serial port initialization
are different with pinouts states. My board don't get
reset signal at first cycle of DTR pinout moving.
And I add this moving to initalization cycle.
1.17 2004-10-21 Changes by Cyril Holweck
Divide main, take out the real programming function, that can
also be used by a target to copy its own code to another.
1.18 2004-10-26 Changes by Cyril Holweck
Added a "G 0 A\r\n" at end of programming to run code.
1.19 2004-11-03 Changes by Robert Adsett
Add support for Analog Devices.
Separate file load from programming.
Change from a debug on/off flag to debug level
Remove if (debug) tests and replace with DebugPrintf
statements.
Change serial I/O and timing so that the system
dependancies are isolated to a few portability functions.
Add support for binary serial I/O.
Add doxygen support.
1.20 2004-11-07 Preparation for multiport booting (factory support)
1.21 2004-11-08 Bugfix from Robert Adsett
BinaryLength was not initialized
1.22 2004-11-08 Changes from Cyril Holweck / Evgeny Sinelnikov
Forgotten IspEnvironment-> and bugfixes if COMPILE_FOR_LINUX
If COMPILE_FOR_LPC21, PhilipsDownload() 'acts as' main():
- it should not be static and should return int.
- no sub-function can use exit() but only return ()
Use 'char' instead of 'byte' ;)
1.23 2005-01-16 Build in automatic detection of LPC chiptype
(needed for 256 KByte support)
1.24B 2005-06-02 Changes by Thiadmer Riemersma: completed support for other
chip types (LPC213x series and others).
1.24C 2005-06-11 Changes by Thiadmer Riemersma: added the device ID codes for
chip types LPC2131 and LPC2132.
1.25 2005-06-19 Martin Maurer: Setup more parameters in DCB,
otherwise wrong code is downloaded (only Windows and Cygwin)
when a previous program has changed these parameters
Check exact string of "G 0 A\r\n0\r\n" instead of whole received buffer,
to prevent checking of already received by program start
(error on running program, but reports CMD_SUCCESS)
Add ifdefs for all baudrates (needed only for high baudrate,
which seem to be not available on Macs...)
1.26 2005-06-26 Martin Maurer:
Correct check again: "G 0 A\r\n0\r\n" is cutted, because of reboot
(error on running program, but reports CMD_SUCCESS)
1.27 2005-06-29 Martin Maurer:
Add LPC chip ID's (thanks to Robert from Philips) for
missing LPC213x and upcoming new LPC214x chips
(currently untested, because i don't have access to these chips,
please give me feedback !)
1.28 2005-07-27 Anders Rosvall / Embedded Artists AB:
Changed the reset timeout to 500 ms when entering the bootloader.
Some external reset controllers have quite long timeout periods,
so extening the timeout delay would be a good thing.
1.29 2005-09-14 Rob Jansen:
Added functionality to download to RAM and run from there.
In LoadFile() added record types 04 (Extended Linear Address Record)
and 05 (Start Linear Address Record), added address offset
(IspEnvironment->BinaryOffset) and start address (...->StartAddress).
Changed PhilipsDownload to skip all Flash prepare/erase/copy commands.
Note: Tested with VC7 only
1.30 2005-10-04 Rob Jansen:
- forgot to change the version string in 1.29
- Wrong text in LoadFile corrected (printed text mentions record type 05,
this should be 04
- Changed LoadFile to accept multiple record types 04
- Changed LoadFile to check on memory size, will not load more than x MB
if linear extended address records are used
1.31 2005-11-13 Martin Maurer: Thanks to Frank Gutmann
Updated number of sectors in device table
for LPC2194, LPC2292 and LPC2294
1.32 2005-12-02 Martin Maurer: Corrected missing control of RTS/DTR
in case user selected -termonly and -control
Small correction (typo in debug)
1.33 2006-10-01 Jean-Marc Koller:
Added support for MacOS X (difference on how to set termios baudrate).
1.34 2006-10-01 Cyril Holweck:
Made it compile again for lpc21isp
Added const keyword to constant variables to make it better
code for embeded target. (decrease RAM usage)
Replaced all regular call to printf() by DebugPrintf()
Removed call to scanf() (not much usefull and cost a lot to my target)
1.35 2006-22-01 Cyril Holweck
Added feature for LPC21: will start downloading at Sector 1 and upward,
to finish with Sector 0, the one containing the checksum controling BSL entry
1.36 2006-25-01 Cyril Holweck
PhilipsDownload() will now return a unique error code for each error
1.37 2006-10-03 Jeroen Domburg
Added LPC2103 (and only the 2103, I can't find the IDs for 2101/2102)
Corrected a loop which occured if the program completely fits in sector 0
1.38 2007-01-05 Ray Molenkamp
Added feature for LPC21: Wipe entire device before programming to enable
reflashing of chips with the lpc codeprotection feature enabled.
1.39 2007-01-12 Martin Maurer
Added initial support for new processors LPC23xx and LPC24xx
1.40 2007-01-22 Martin Maurer
Correction of chip id of LPC2458
1.41 2007-01-28 Jean-Marc Koller
Modified Terminal() to disable ECHO with termios only once, instead of
modifying and restoring termios in each getch and kbhit call (which caused
a strange echo behaviour in MacOS X).
1.42 2007-01-28 Rob Probin
Added -localecho command to allow local echoing in terminal mode for use
where target does not echo back keystrokes.
1.43 2007-01-29 Martin Maurer
Moved keyboard handling routines to own subroutines,
so they can be used during aborting synchronisation.
Newest cygwin made problems, StringOscillator always contained '\0x0d'
at the end, when calling lpc21isp from batch file
1.44 2007-02-23 Yang Yang
Added feature for LPC21: Verify the data in Flash after every writes
to sector. To detect errors in writing to Flash ROM.
1.45 2007-02-25 Martin Maurer
Replace printf syntax of DumpString by a simple pointer to a string
printf syntax is a nice thing, but it is not working :-(
and therefore makes debugging much more difficult...
Moved VERSION_STR to top of file to avoid possible cosmetical errors
1.46 2007-02-25 Martin Maurer
Again corrected debug output: should solve output of
(FFFFFFB5) instead of (B5)
1.47 2007-02-27 Robert Adsett
Raised timeout on AD send packet function.
1.48 2007-04-20 Martin Maurer
Thanks to Josef Wolf for preventing to overwrite over end of array
1.49 2007-10-16 New Option -halfduplex allow single wire using.
Implemented and tested only for Windows. Data Resend implemented.
1.50 2007-10-31 Changes by Simon Ellwood
Formated the code for readablity
Fixed some c++ compiler issues
1.51 2007-11-20 Changes by Simon Ellwood
Split into seperate files
Made more modular so when used in an embedded mode only the required code is built
1.52 2008-01-22 Changes by Manuel Koeppen
Made compileable again for linux and windows
Fixed bug in ClearSerialPortBuffers (linux)
1.53 2008-02-25 Changes by Michael Roth
Get priority of debug messages with -control right
1.54 2008-03-03 Martin Maurer
Try to bring lpc21isp back to a useable state in Windows, Cygwin, Linux and Mac OS.
Merged in changes by Erika Stefanini, which were done only for old version 1.49:
Added device ids for revision B chips
1.55 2008-03-03 Martin Maurer
Thanks to Fausto Marzoli, bugfix for compiling latest version under Linux
1.56 2008-04-01 Steve Franks
Integrate FreeBSD patch.
Add support for swapping and/or inverting RTS & DTR
1.57 2008-04-06 Mauricio Scaff
Changed OpenSerialPort to work with MacOS
Corrected the number of sectors in some 512K devices (28 instead of 27)
Added support for LPC2387 and LPC2388
Defined BL error 19 (Code Protected)
1.58 2008-05-10 Herbert Demmel [email protected]
I had the special requirement to integrate the program into my own Windows
software compiled with Borland C++ Builder 5. I had to do some minor changes
for Borland (see defined __BORLANDC__) and modified to code slightly to have
some simple callbacks for screen i/o (see define INTEGRATED_IN_WIN_APP).
Please note that I do *not* check / modify the part for AnalogDevices !!
Besides that I fixed some minor issues:
added dcb.fOutxCtsFlow = FALSE and dcb.fOutxDsrFlow = FALSE (sometimes required)
Now comparing one character less of answer to "Now launching ... code" command
1.59 2008-07-07 Peter Hayward
Fixed freeze under Windows XP SP2 by removing redundant call to SetCommMask.
1.60 2008-07-21 Martin Maurer
Added uptodate part ids for LPC2458, LPC2468 and LPC2478
Add comment "obsolete" for older part ids for LPC2458 and LPC2468
Add ", " between compile date and time
1.61 2008-10-21 Fausto Marzoli (thanks to Geoffrey Wossum for the patches)
Fix for compiling latest version under Linux and "ControlLinesSwapped" issue
1.62 2008-11-19 Martin Maurer
Added (untested) support for LPC2109
Added (untested) support for LPC2361 / LPC2362
Heavy update of part identification number of LPC23xx and LPC24xx
Correct bug, that hex file must exist, when "-detectonly" is used
Correct Makefile.vc: use /Fe instead of -o
1.63 2008-11-23 Martin Maurer
Changed to GNU Lesser General Public License
1.64 2009-01-19 Steve Franks
__FREEBSD__ changed to __FreeBSD__ at some point, plus other com port fixes
1.65 2009-03-26 Vito Marolda
Added pre-erasure of sector 0 to invalidate checksum before starting
modification of the other sectors, so that the bootloader restarts
if programming gets aborted while writing on a non-empty part.
1.66 2009-03-26 Vito Marolda
Corrected interpretation of intel hex record 03 which is execution start address
and not data segment address
1.67 2009-04-19 SASANO Takayoshi
Add OpenBSD support
1.68 2009-05-17 Martin Maurer
Merge in changes done by Bruno Quoitin (baudrate problem when __APPLE__ is used)
Remove TABs from source code and replaced them with spaces
1.69 2009-06-18 Martin Maurer
Add support for LPC17xx devices
1.70 2009-06-29 Martin Maurer
Further improvement of LPC17xx support
Workaround for booter (4.1) of LPC17xx, which does not echo all sent characters (0D,0A,...)
ISP command GO seems to be broken:
Sending 'G 196 T(0A)'
Answer(Length=15): 'G 196 T(0A)0(0D)(0A)'
leads to 'prefetch_abort_exception(0D)(0A)1FFF07A5'
No solution known...need your help here...
Manual workaround: Use DTR and RTS toggling to start application (e.g. 2 batch files)
1.71 2009-07-19 Martin Maurer
Added LPC17xx with CPUID starting with 0x26 (not according user manual)
1.72 2009-09-14 Martin Maurer
Add support for LPC13xx devices
1.73 2009-09-14 Martin Maurer
Correct again (hopefully the last time) the CPUIDs for some LPC17xx devices
(Now according to User Manual LPC17xx Version 00.07 (31 July 2009))
1.74 2009-09-14 Mario Ivancic
Added support for multiple HEX files, besed on internal version 1.37B.
NOTE: this feature is used in production in 1.37B but is not tested in this version.
Added numeric debug level command line switch -debugn, n=[0-5]
Added command line scitch -try n to specify nQuestionMarks limit. Default: 100
Merged in DoNotStart patch from cgommel_new
Static functions declarations moved from lpc21isp.h to this file
Modified LoadFile() to return error_code instead exit(1)
Removed IspEnvironment.debug_level, all code uses global debug_level
1.75 2010-01-05 Martin Maurer
Added support for LPC11xx devices (not tested at all)
Changed Product in LPC_DEVICE_TYPE from number to string to distinguish new LPC11 devices
Changed "unsigned" to "unsigned int" in LPC_DEVICE_TYPE
1.76 2010-02-01 Published test version without source code
1.77 2010-02-01 Martin Maurer
Corrected chip id of LPC1342 and LPC1343
Added a new chip type for LPC11xx and LPC13xx microcontrollers
Use higher area of RAM with LPC11xx and LPC13xx, because lower RAM is occupied by ISP
Add code to lpcprog.c to read unique id, but not yet activate.
Adapt block sizes for copying for each model of LPC11xx and LPC13xx
1.78 2010-02-16 Martin Maurer
Corrected chip id of LPC1751
Added support for LPC1759, LPC1767 and LPC1769
1.79 2010-02-19 Andrew Pines
Added __APPLE__ flag to CFLAGS in Makefile to detect and handle OS X
Added -Wall to Makefile to report warnings more comprehensively
Added #define in lpc21isp.h to substitute strnicmp with strncasecmp (needed for Unix)
Fixed a few format specifiers in lpcprog.c to eliminate some warnings
1.80 2010-03-04 Philip Munts
Added entries to LPCtypes[] in lpcprog.c for obsolete revisions of LPC2364/6/8/78.
Added entry to LPCtypes[] in lpcprog.c for new LPC2387.
1.81 2011-03-30 Mario Ivancic
As per message #517 from Thiadmer Riemersma, removed WaitForWatchDog and WatchDogSeconds
in PhilipsDownload().
1.82 2011-06-25 Moses McKnight
Corrected MaxCopySize for a number of the LPC11xx series
Added support for several more LPC11xx and LPC11Cxx series
1.83 2011-08-02 Martin Maurer
Thanks to Conurus for detecting and fixing a bug with patching checksum
(patching was too early, chip id was not yet available)
(Re-)Added code to start downloaded via "G 0 T", when using LPC1xxx
(Starting code at position 0 seems to work, compare to comment of version 1.70)
Changed some occurances of Philips to NXP
Added -static to Makefile (thanks to Camilo)
Added support for LPC1311/01 and LPC1313/01 (they have separate identifiers)
Correct flash size of LPC1342 to 16 KByte (thanks to Decio)
Abort programming when unknown NXP chip id is detected
1.84 2012-09-27 Philip Munts
Added chip id's for more LPC11xx parts, per UM10398 Rev. 11 26 July 2012
1.85 2012-12-13 Philip Munts
Fixed conditional compilation logic in lpc21isp.h to allow compiling for ARM Linux.
1.86 2012-12-14 diskrepairman
Added devices: LPC1114/203 LPC1114/303 LPC1114/323 LPC1114/333 LPC1115/303
1.87 2012-12-18 Philip Munts
Added a section of code to ResetTarget() in lpc21isp.c to allow using Linux GPIO pin
to control reset and ISP.
1.88 2013-04-25 Torsten Lang, Uwe Schneider GmbH
Fixed answer evaluation
Added sector tables for LPC1833
XON/XOFF handling according to LPC manual
Changed COMMTIMEOUTS settings according to MS help
Changed waiting code from tick counting to system time usage
Set MM timers to 1ms resolution (otherwise waiting in the serial driver is limited to multiples of 10ms)
Send all commands with <CR><LF> according to NXP UM
Change answer evaluation to match at least LPC17xx and LPC18xx families (LPC17xx just mirrors the first character of
the LF sequence, LPC18xx mirrors the first character and adds an <LF> which then will lead to a <CR><LF><LF>
sequence, all other lines are terminated with <CR><LF> as documented)
Change answer formatting by filtering leading <LF> characters because they can be left over from a previous response
Store residual data of an answer (required for the J command which will deliver two words in case of the LPC18xx)
Expanded configuration table by second identification word and usage flag
Do a two stage scan in case that a device with two identification words is detected
1.89 2013-06-27 Martin Maurer
Thanks to Manuel and Henri for bugfixes and speed-ups
Bugfix: In case of LPC8XX, XON/XOFF handling must be switched off,
otherwise download gets broken, because XON/XOFF are filtered out...
1.90 2013-06-27 Martin Maurer
Add checksum calculation for LPC8XX
winmm function only available in MSVC, put ifdefs around
Workaround for lost characters of LPC8XX
1.91 2013-06-28 Torsten Lang, Uwe Schneider GmbH
Minor bugfix for the residual data handling
1.92 2013-06-29 Martin Maurer
Thanks to Phil for reporting Linux compile errors
Update README
1.93 2013-07-05 Andrew Pines
changed Makefile to exclude "-static" from CFLAGS when building for OS X
changed serial timeout for *nix to use select
added -boothold argument to assert ISP throughtout programming sequence
added support for -try<n> command line argument (was in help, didn't actually work)
1.94 2013-08-10 Martin Maurer
Add (assumed) part id values for LPC4333 and LPC4337
Correct table entries for all LPC43xx part id numbers
(missing flag for two word part ids and second word for LPC4333 and LPC4353)
Merge in optimization (thanks to Stefan) to skip empty sectors
Correct help output of "-boothold"
Add workaround table entry for LPC4357 and word1 equal to 0x0EF60000
Bugfix for wrong check of word0/word1 combination
Correct a lot entries in lpc property table of LPC18xx and LPC43xx
LPC18xx and LPC43xx: Add warning message, that wipe erases only bank A
1.95 2014-01-08 Martin Maurer
Add a lot of new chip ids for LPC1763, LPC11Exx, LPC11Uxx
(completely untested because I don't have these chips)
Corrected checking of 2 field chip ids (must be masked)
Corrected Makefile (-static)
Move while directory with files into a subdirectory
1.96 2014-01-08 Martin Maurer merged changes by Moses McKnight
Added devices: LPC1315, LPC1316, LPC1317, LPC1345, LPC1346, LPC1347
Add .gitignore file (MM: Removed *.layout)
Remove lpc21isp.depend
2014-01-08 Martin Maurer merged bugfix by smartavionics:
- Wrong length in ReceiveComPort
- Enable SerialTimeoutTick
2014-01-08 Martin Maurer merged bugfix by justyn:
- Fix the total sector size fields for 1114.../323 and 1114.../333
2014-01-08 Martin Maurer merged bugfix by imyller:
- Support for bad UARTs: added -writedelay command-line switch
1.97 2014-01-09 Martin Maurer
Add some new chip ids for LPC11xx
Updated .gitignore file (Now with ignored *.layout)
Removed *.layout from lpc21isp project
Removed *.depend from lpc21isp project
2016-01-17 Cristiano Rodrigues
Add some new chip ids for LPC40xx
2018-04-23 Jürgen Stuber
Add support for LPC83x, LPC84x and LPC80x
2018-08-27 Jürgen Stuber
Add support for LP15xx
*/
// Please don't use TABs in the source code !!!
// Don't forget to update the version string that is on the next line
#define VERSION_STR "1.97"
#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
static char RxTmpBuf[256]; // save received data to this buffer for half-duplex
char * pRxTmpBuf = RxTmpBuf;
#endif
#if !defined COMPILE_FOR_LPC21
int debug_level = 2;
#endif
static void ControlModemLines(ISP_ENVIRONMENT *IspEnvironment, unsigned char DTR, unsigned char RTS);
static unsigned char Ascii2Hex(unsigned char c);
#ifdef COMPILE_FOR_WINDOWS
static void SerialTimeoutSet(ISP_ENVIRONMENT *IspEnvironment, unsigned timeout_milliseconds);
static int SerialTimeoutCheck(ISP_ENVIRONMENT *IspEnvironment);
#endif // COMPILE_FOR_WINDOWS
static int AddFileHex(ISP_ENVIRONMENT *IspEnvironment, const char *arg);
static int AddFileBinary(ISP_ENVIRONMENT *IspEnvironment, const char *arg);
static int LoadFile(ISP_ENVIRONMENT *IspEnvironment, const char *filename, int FileFormat);
/************* Portability layer. Serial and console I/O differences */
/* are taken care of here. */
#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
static void OpenSerialPort(ISP_ENVIRONMENT *IspEnvironment)
{
DCB dcb;
COMMTIMEOUTS commtimeouts;
#ifdef _MSC_VER
/* Torsten Lang 2013-05-06 Switch to higher timer resolution (we want to use 1ms timeouts in the serial device driver!) */
(void)timeBeginPeriod(1UL);
#endif // _MSC_VER
IspEnvironment->hCom = CreateFile(IspEnvironment->serial_port, GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (IspEnvironment->hCom == INVALID_HANDLE_VALUE)
{
DebugPrintf(1, "Can't open COM-Port %s ! - Error: %ld\n", IspEnvironment->serial_port, GetLastError());
exit(2);
}
DebugPrintf(3, "COM-Port %s opened...\n", IspEnvironment->serial_port);
GetCommState(IspEnvironment->hCom, &dcb);
dcb.BaudRate = atol(IspEnvironment->baud_rate);
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fOutX = TRUE; // TL TODO - according to LPC manual! FALSE;
dcb.fInX = TRUE; // TL TODO - according to LPC manual! FALSE;
dcb.fNull = FALSE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
// added by Herbert Demmel - iF CTS line has the wrong state, we would never send anything!
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
if (SetCommState(IspEnvironment->hCom, &dcb) == 0)
{
DebugPrintf(1, "Can't set baudrate %s ! - Error: %ld", IspEnvironment->baud_rate, GetLastError());
exit(3);
}
/*
* Peter Hayward 02 July 2008
*
* The following call is only needed if the WaitCommEvent
* or possibly the GetCommMask functions are used. They are
* *not* in this implimentation. However, under Windows XP SP2
* on my laptop the use of this call causes XP to freeze (crash) while
* this program is running, e.g. in section 5/6/7 ... of a largish
* download. Removing this *unnecessary* call fixed the problem.
* At the same time I've added a call to SetupComm to request
* (not necessarity honoured) the operating system to provide
* large I/O buffers for high speed I/O without handshaking.
*
* SetCommMask(IspEnvironment->hCom,EV_RXCHAR | EV_TXEMPTY);
*/
SetupComm(IspEnvironment->hCom, 32000, 32000);
SetCommMask(IspEnvironment->hCom, EV_RXCHAR | EV_TXEMPTY);
// Torsten Lang 2013-05-06: ReadFile may hang indefinitely with MAXDWORD/0/1/0/0 on FTDI devices!!!
commtimeouts.ReadIntervalTimeout = MAXDWORD;
commtimeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
commtimeouts.ReadTotalTimeoutConstant = 1;
commtimeouts.WriteTotalTimeoutMultiplier = 0;
commtimeouts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(IspEnvironment->hCom, &commtimeouts);
}
#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
#if defined COMPILE_FOR_LINUX
static void OpenSerialPort(ISP_ENVIRONMENT *IspEnvironment)
{
IspEnvironment->fdCom = open(IspEnvironment->serial_port, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (IspEnvironment->fdCom < 0)
{
int err = errno;
DebugPrintf(1, "Can't open COM-Port %s ! (Error: %dd (0x%X))\n", IspEnvironment->serial_port, err, err);
exit(2);
}
DebugPrintf(3, "COM-Port %s opened...\n", IspEnvironment->serial_port);
/* clear input & output buffers, then switch to "blocking mode" */
tcflush(IspEnvironment->fdCom, TCOFLUSH);
tcflush(IspEnvironment->fdCom, TCIFLUSH);
fcntl(IspEnvironment->fdCom, F_SETFL, fcntl(IspEnvironment->fdCom, F_GETFL) & ~O_NONBLOCK);
tcgetattr(IspEnvironment->fdCom, &IspEnvironment->oldtio); /* save current port settings */
bzero(&IspEnvironment->newtio, sizeof(IspEnvironment->newtio));
IspEnvironment->newtio.c_cflag = CS8 | CLOCAL | CREAD;
#if defined(__FreeBSD__) || defined(__OpenBSD__)
if(cfsetspeed(&IspEnvironment->newtio,(speed_t) strtol(IspEnvironment->baud_rate,NULL,10))) {
DebugPrintf(1, "baudrate %s not supported\n", IspEnvironment->baud_rate);
exit(3);
};
#else
#ifdef __APPLE__
#define NEWTERMIOS_SETBAUDARTE(bps) IspEnvironment->newtio.c_ispeed = IspEnvironment->newtio.c_ospeed = bps;
#else
#define NEWTERMIOS_SETBAUDARTE(bps) IspEnvironment->newtio.c_cflag |= bps;
#endif
switch (atol(IspEnvironment->baud_rate))
{
#ifdef B1152000
case 1152000: NEWTERMIOS_SETBAUDARTE(B1152000); break;
#endif // B1152000
#ifdef B576000
case 576000: NEWTERMIOS_SETBAUDARTE(B576000); break;
#endif // B576000
#ifdef B230400
case 230400: NEWTERMIOS_SETBAUDARTE(B230400); break;
#endif // B230400
#ifdef B115200
case 115200: NEWTERMIOS_SETBAUDARTE(B115200); break;
#endif // B115200
#ifdef B57600
case 57600: NEWTERMIOS_SETBAUDARTE(B57600); break;
#endif // B57600
#ifdef B38400
case 38400: NEWTERMIOS_SETBAUDARTE(B38400); break;
#endif // B38400
#ifdef B19200
case 19200: NEWTERMIOS_SETBAUDARTE(B19200); break;
#endif // B19200
#ifdef B9600
case 9600: NEWTERMIOS_SETBAUDARTE(B9600); break;
#endif // B9600
// Special value
// case 32000: NEWTERMIOS_SETBAUDARTE(32000); break;
default:
{
DebugPrintf(1, "unknown baudrate %s\n", IspEnvironment->baud_rate);
exit(3);
}
}
#endif
IspEnvironment->newtio.c_iflag = IGNPAR | IGNBRK | IXON | IXOFF;
IspEnvironment->newtio.c_oflag = 0;
/* set input mode (non-canonical, no echo,...) */
IspEnvironment->newtio.c_lflag = 0;
cfmakeraw(&IspEnvironment->newtio);
IspEnvironment->newtio.c_cc[VTIME] = 1; /* inter-character timer used */
IspEnvironment->newtio.c_cc[VMIN] = 0; /* blocking read until 0 chars received */
tcflush(IspEnvironment->fdCom, TCIFLUSH);
if(tcsetattr(IspEnvironment->fdCom, TCSANOW, &IspEnvironment->newtio))
{
DebugPrintf(1, "Could not change serial port behaviour (wrong baudrate?)\n");
exit(3);
}
}
#endif // defined COMPILE_FOR_LINUX
#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
static void CloseSerialPort(ISP_ENVIRONMENT *IspEnvironment)
{
CloseHandle(IspEnvironment->hCom);
#ifdef _MSC_VER
/* Torsten Lang 2013-05-06 Switch back timer resolution */
(void)timeEndPeriod(1UL);
#endif // _MSC_VER
}
#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
#if defined COMPILE_FOR_LINUX
static void CloseSerialPort(ISP_ENVIRONMENT *IspEnvironment)
{
tcflush(IspEnvironment->fdCom, TCOFLUSH);
tcflush(IspEnvironment->fdCom, TCIFLUSH);
tcsetattr(IspEnvironment->fdCom, TCSANOW, &IspEnvironment->oldtio);
close(IspEnvironment->fdCom);
}
#endif // defined COMPILE_FOR_LINUX
#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
void ControlXonXoffSerialPort(ISP_ENVIRONMENT *IspEnvironment, unsigned char XonXoff)
{
DCB dcb;
GetCommState(IspEnvironment->hCom, &dcb);
if(XonXoff)
{
dcb.fOutX = TRUE;
dcb.fInX = TRUE;
}
else
{
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
}
if (SetCommState(IspEnvironment->hCom, &dcb) == 0)
{
DebugPrintf(1, "Can't set XonXoff ! - Error: %ld", GetLastError());
exit(3);
}
}
#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
#if defined COMPILE_FOR_LINUX
void ControlXonXoffSerialPort(ISP_ENVIRONMENT *IspEnvironment, unsigned char XonXoff)
{
if(tcgetattr(IspEnvironment->fdCom, &IspEnvironment->newtio))
{
DebugPrintf(1, "Could not get serial port behaviour\n");
exit(3);
}
if(XonXoff)
{
IspEnvironment->newtio.c_iflag |= IXON;
IspEnvironment->newtio.c_iflag |= IXOFF;
}
else
{
IspEnvironment->newtio.c_iflag &= ~IXON;
IspEnvironment->newtio.c_iflag &= ~IXOFF;
}
if(tcsetattr(IspEnvironment->fdCom, TCSANOW, &IspEnvironment->newtio))
{
DebugPrintf(1, "Could not set serial port behaviour\n");
exit(3);
}
}
#endif // defined COMPILE_FOR_LINUX
/***************************** SendComPortBlock *************************/
/** Sends a block of bytes out the opened com port.
\param [in] s block to send.
\param [in] n size of the block.
*/
void SendComPortBlock(ISP_ENVIRONMENT *IspEnvironment, const void *s, size_t n)
{
#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
unsigned long realsize;
size_t m;
unsigned long rxsize;
char * pch;
char * rxpch;
#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
DumpString(4, s, n, "Sending ");
#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
if (IspEnvironment->HalfDuplex == 0)
{
WriteFile(IspEnvironment->hCom, s, n, &realsize, NULL);
}
else
{
pch = (char *)s;
rxpch = RxTmpBuf;
pRxTmpBuf = RxTmpBuf;
// avoid buffer otherflow
if (n > sizeof (RxTmpBuf))
n = sizeof (RxTmpBuf);
for (m = 0; m < n; m++)
{
WriteFile(IspEnvironment->hCom, pch, 1, &realsize, NULL);
if ((*pch != '?') || (n != 1))
{
do
{
ReadFile(IspEnvironment->hCom, rxpch, 1, &rxsize, NULL);
}while (rxsize == 0);
}
pch++;
rxpch++;
}
*rxpch = 0; // terminate echo string
}
#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21
write(IspEnvironment->fdCom, s, n);
#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_LPC21
if (IspEnvironment->WriteDelay == 1)
{
Sleep(100); // 100 ms delay after each block (makes lpc21isp to work with bad UARTs)
}
}
/***************************** SendComPort ******************************/
/** Sends a string out the opened com port.
\param [in] s string to send.
*/
void SendComPort(ISP_ENVIRONMENT *IspEnvironment, const char *s)
{
SendComPortBlock(IspEnvironment, s, strlen(s));
}
/***************************** SerialTimeoutTick ************************/
/** Performs a timer tick. In this simple case all we do is count down
with protection against underflow and wrapping at the low end.
*/
static void SerialTimeoutTick(ISP_ENVIRONMENT *IspEnvironment)
{
if (IspEnvironment->serial_timeout_count <= 1)
{
IspEnvironment->serial_timeout_count = 0;
}
else
{
IspEnvironment->serial_timeout_count--;
}
}
/***************************** ReceiveComPortBlock **********************/
/** Receives a buffer from the open com port. Returns all the characters
ready (waits for up to 'n' milliseconds before accepting that no more
characters are ready) or when the buffer is full. 'n' is system dependant,
see SerialTimeout routines.
\param [out] answer buffer to hold the bytes read from the serial port.
\param [in] max_size the size of buffer pointed to by answer.
\param [out] real_size pointer to a long that returns the amout of the
buffer that is actually used.
*/
static void ReceiveComPortBlock(ISP_ENVIRONMENT *IspEnvironment,
void *answer, unsigned long max_size,
unsigned long *real_size)
{
char tmp_string[32];
#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
if (IspEnvironment->HalfDuplex == 0)
ReadFile(IspEnvironment->hCom, answer, max_size, real_size, NULL);
else
{
*real_size = strlen (pRxTmpBuf);
if (*real_size)
{
if (max_size >= *real_size)
{
strncpy((char*) answer, pRxTmpBuf, *real_size);
RxTmpBuf[0] = 0;
pRxTmpBuf = RxTmpBuf;
}
else
{
strncpy((char*) answer, pRxTmpBuf, max_size);
*real_size = max_size;
pRxTmpBuf += max_size;
}
}
else
ReadFile(IspEnvironment->hCom, answer, max_size, real_size, NULL);
}
#endif // defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
#if defined COMPILE_FOR_LPC21
*real_size = read(IspEnvironment->fdCom, answer, max_size);
#endif // defined COMPILE_FOR_LPC21
#if defined COMPILE_FOR_LINUX
{
fd_set readSet;
struct timeval timeVal;
int ret;
// wait up to 500 ms or until our data is ready
FD_ZERO(&readSet);
FD_SET(IspEnvironment->fdCom, &readSet);
timeVal.tv_sec = 0;
timeVal.tv_usec = 500 * 1000;
ret = select(IspEnvironment->fdCom + 1, &readSet, NULL, NULL, &timeVal);
if (ret == -1)
{
sprintf(tmp_string, "Select error: %d", errno);
DumpString(5, 0, 0, tmp_string);
*real_size = 0;
}
else if (ret == 0)
{
*real_size = 0;
}
else
{
*real_size = read(IspEnvironment->fdCom, answer, max_size);
}
}
#endif // defined COMPILE_FOR_LINUX
sprintf(tmp_string, "Read(Length=%ld): ", (*real_size));
DumpString(5, answer, (*real_size), tmp_string);
if (*real_size == 0)
{
SerialTimeoutTick(IspEnvironment);
}
}
/***************************** SerialTimeoutSet *************************/
/** Sets (or resets) the timeout to the timout period requested. Starts
counting to this period. This timeout support is a little odd in that the
timeout specifies the accumulated deadtime waiting to read not the total
time waiting to read. They should be close enought to the same for this
use. Used by the serial input routines, the actual counting takes place in
ReceiveComPortBlock.
\param [in] timeout_milliseconds the time in milliseconds to use for
timeout. Note that just because it is set in milliseconds doesn't mean
that the granularity is that fine. In many cases (particularly Linux) it
will be coarser.
*/
static void SerialTimeoutSet(ISP_ENVIRONMENT *IspEnvironment, unsigned timeout_milliseconds)
{
#if defined COMPILE_FOR_LINUX
IspEnvironment->serial_timeout_count = timeout_milliseconds / 100;
#elif defined COMPILE_FOR_LPC21
IspEnvironment->serial_timeout_count = timeout_milliseconds * 200;
#else
#ifdef _MSC_VER
IspEnvironment->serial_timeout_count = timeGetTime() + timeout_milliseconds;
#else
IspEnvironment->serial_timeout_count = timeout_milliseconds;
#endif // _MSC_VER
#endif
}
/***************************** SerialTimeoutCheck ***********************/
/** Check to see if the serial timeout timer has run down.
\retval 1 if timer has run out.
\retval 0 if timer still has time left.
*/
static int SerialTimeoutCheck(ISP_ENVIRONMENT *IspEnvironment)
{
#if defined COMPILE_FOR_WINDOWS || defined COMPILE_FOR_CYGWIN
#ifdef _MSC_VER
if ((signed long)(IspEnvironment->serial_timeout_count - timeGetTime()) < 0)
{
return 1;
}
#else
if (IspEnvironment->serial_timeout_count == 0)
{
return 1;
}
#endif // _MSC_VER
#else
if (IspEnvironment->serial_timeout_count == 0)
{
return 1;
}
#endif
return 0;
}
#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
/***************************** getch ************************************/
/** Replacement for the common dos function of the same name. Reads a
single unbuffered character from the 'keyboard'.
\return The character read from the keyboard.
*/
int getch(void)
{
char ch;
/* Read in one character */
read(0,&ch,1);
return ch;
}
#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
/***************************** kbhit ************************************/
/** Replacement for the common dos function of the same name. Indicates if
there are characters to be read from the console.
\retval 0 No characters ready.
\retval 1 Characters from the console ready to be read.
*/
int kbhit(void)
{
/* return 0 for no key pressed, 1 for key pressed */
int return_value = 0;
/* time struct for the select() function, to only wait a little while */
struct timeval select_time;
/* file descriptor variable for the select() call */
fd_set readset;
/* we're only interested in STDIN */
FD_ZERO(&readset);
FD_SET(STDIN_FILENO, &readset);
/* how long to block for - this must be > 0.0, but could be changed
to some other setting. 10-18msec seems to work well and only
minimally load the system (0% CPU loading) */
select_time.tv_sec = 0;
select_time.tv_usec = 10;
/* is there a keystroke there? */
if (select(1, &readset, NULL, NULL, &select_time))
{
/* yes, remember it */
return_value = 1;
}
/* return with what we found out */
return return_value;
}
struct termios keyboard_origtty;
#endif // defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
/***************************** PrepareKeyboardTtySettings ***************/
/** Set the keyboard tty to be able to check for new characters via kbhit
getting them via getch
*/
void PrepareKeyboardTtySettings(void)
{
#if defined COMPILE_FOR_LINUX || defined COMPILE_FOR_CYGWIN
/* store the current tty settings */