-
Notifications
You must be signed in to change notification settings - Fork 17
/
xmegaBOOT.c
2721 lines (2190 loc) · 86.8 KB
/
xmegaBOOT.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
/////////////////////////////////////////////////////////////////////////////////
// XMEGA BOOT LOADER - modified from the Arduino 1.05 bootloader ATmegaBOOT_xx8.c
// by Bob Frazier, S.F.T. Inc.. Some xmega-specific code was
// originally developed under contract for Boardformula, Inc.
// for their xmega-based device, with similar GPL licensing.
// This program must be licensed under GPLv2 or later (see comments below)
/////////////////////////////////////////////////////////////////////////////////
// This bootloader has been tested with the following processors:
//
// ATxmega64D4
// ATxmega32E5
// ATxmega128A1
// ATxmega128A4U (non-USB mode)
//
/////////////////////////////////////////////////////////////////////////////////
// XMEGA CHANGES:
//
// - apply equivalent fixes as the Adafruit bootloader does
// (blink, flash bypass, WATCHDOG_MODS)
// - special '115k baud only' baud rate code (only rate supported at this time)
// - by default, built-in LED is on PORTR pin 1
// - also by default, the serial port is on PORTD (pins 2,3) only for flashing
// - XMEGA-specific NVRAM write functions
// THIS is the _GENERIC_ version. It requires some definitions to work properly
//----------------------------------------------------------
// ORIGINAL COMMENT BLOCK FROM Arduino bootloader
// this is being retained for licensing reasons
/**********************************************************/
/* Serial Bootloader for Atmel megaAVR Controllers */
/* */
/* tested with ATmega8, ATmega128 and ATmega168 */
/* should work with other mega's, see code for details */
/* */
/* ATmegaBOOT.c */
/* */
/* */
/* 20090308: integrated Mega changes into main bootloader */
/* source by D. Mellis */
/* 20080930: hacked for Arduino Mega (with the 1280 */
/* processor, backwards compatible) */
/* by D. Cuartielles */
/* 20070626: hacked for Arduino Diecimila (which auto- */
/* resets when a USB connection is made to it) */
/* by D. Mellis */
/* 20060802: hacked for Arduino by D. Cuartielles */
/* based on a previous hack by D. Mellis */
/* and D. Cuartielles */
/* */
/* Monitor and debug functions were added to the original */
/* code by Dr. Erik Lins, chip45.com. (See below) */
/* */
/* Thanks to Karl Pitrich for fixing a bootloader pin */
/* problem and more informative LED blinking! */
/* */
/* For the latest version see: */
/* http://www.chip45.com/ */
/* */
/* ------------------------------------------------------ */
/* */
/* based on stk500boot.c */
/* Copyright (c) 2003, Jason P. Kyle */
/* All rights reserved. */
/* see avr1.org for original file and information */
/* */
/* This program 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 2 of the License, or */
/* (at your option) any later version. */
/* */
/* This program 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 along with this program; if not, write */
/* to the Free Software Foundation, Inc., */
/* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* */
/* Licence can be viewed at */
/* http://www.fsf.org/licenses/gpl.txt */
/* */
/* Target = Atmel AVR m128,m64,m32,m16,m8,m162,m163,m169, */
/* m8515,m8535. ATmega161 has a very small boot block so */
/* isn't supported. */
/* */
/* Tested with m168 */
/**********************************************************/
// some of this code was adapted from ATmel sample source and
// requires the following license information for distribution:
/*
Copyright (c) 2009 Atmel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of Atmel may not be used to endorse or promote products derived
from this software without specific prior written permission.
4. This software may only be redistributed and used in connection with an Atmel
AVR product.
THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
*/
// ---------------------------------------------------------------------------------
// NOTICE - No K&R style coding has been retained. Allman style is used throughout
// ---------------------------------------------------------------------------------
/* some includes */
#include <inttypes.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <avr/eeprom.h>
#include <util/delay.h>
#ifdef USE_CATERINA
///////////////////////////////////////////////////////////////////////////////////////////////
// For Caterina, this requires a USB VID and PID
//
// They are defined via DEVICE_VID and DEVICE_PID definitions. Makefile uses VID and PID
// in order to be compatible with the way that the Caterina bootloader (part of the Arduino
// Core files, see github.com/arduino/ArduinoCore-avr ) is set up.
//
// The Arduino build uses a VID of 0x2341 - reuse of this VID by others is forbidden by USB-IF
// The PID assigned for Caterina bootloaders identifies the device.
//
// The best solution is probably here:
// https://raw.githubusercontent.com/arduino/ArduinoISP/master/usbdrv/USB-IDs-for-free.txt
//
// The VID and PID used by the default pins_arduino.h files for USB-capable xmega's make use
// of these and respond to queries with a proper description of the implementation.
//
// This MAY still create driver problems with Windows(tm), especially Windows 10.
// (Blame Microsoft(r) for that, it's their decision to make life harder for makers)
//
// one solution to the driver problem on Windows has been described (in an online forum)
// "Edited standard Arduino driver for Leonardo, the INF file, editing it to suit our
// requirements.
// Microsoft Inf2Cat to create a CAT file from the INF file, then got a certificate
// from DigiCert.com for code signing. I then used the certificate to sign the CAT
// file, and installed the driver and all is good."
//
// source: https://forum.arduino.cc/index.php?topic=415917.0
//
// Since the VID/PID merely identifies a product, normally with a class driver for USB serial,
// on systems like Linux and FreeBSD this isn't a problem. HOWEVER, Windows isn't very "nice"
// when it comes to implementing class drivers.
//
// However, the Arduino IDE appears to install a CDC/ACM class driver for you, it should be
// possible to use the Arduino drivers if the device class is recognized by Windows.
#if !defined(DEVICE_VID) && !defined(DEVICE_PID)
// see https://raw.githubusercontent.com/arduino/ArduinoISP/master/usbdrv/USB-IDs-for-free.txt
#define DEVICE_VID 0x16c0 /* Van Ooijen Technische Informatica */
#define DEVICE_PID 0x05e1 /* name-based CDC/ACM device */
#endif !defined(DEVICE_VID) && !defined(DEVICE_PID)
#endif // USE_CATERINA
// These function names were derived from equivalent functions supplied
// by ATmel in the 'SPM driver' sample for flashing the xmega
void SP_WaitForSPM(void);
void SP_EraseFlashBuffer(void);
void SP_LoadFlashPage(const uint8_t * data, uint16_t length);
void SP_WriteApplicationPage(uint32_t address);
// for reading NVM data directly (a convenience function)
uint8_t readNVMData(uint8_t cmd, uint16_t iIndex);
//#ifdef USE_STK500V2
//#define BLINK_PERIOD (F_CPU / 160) /* slower blink for STK500V2 and slightly longer delay results */
//#else // USE_STK500V2
#define BLINK_PERIOD (F_CPU / 320) /* faster blink for everyone else, around 0.1 seconds */
//#endif
/* Use the F_CPU and MAX_TIME_COUNT as defined in Makefile */
#ifndef F_CPU
#error you need to define F_CPU and indicate the value with '-D'
#endif // F_CPU
#ifndef MAX_TIME_COUNT
#error you need to define MAX_TIME_COUNT and indicate the value with '-D'
#endif // MAX_TIME_COUNT
/* 20070707: hacked by David A. Mellis - after this many errors give up and launch application */
#define MAX_ERROR_COUNT 5
/* set the UART baud rate, default 115200 */
#ifndef BAUD_RATE
#define BAUD_RATE 115200
#endif
/* SW_MAJOR and MINOR needs to be updated from time to time to avoid warning message from AVR Studio */
/* never allow AVR Studio to do an update !!!! */
#define HW_VER 0x02
#define SW_MAJOR 0x01
#define SW_MINOR 0x10
// for these bit values see D manual section 11.12.15
// do NOT use 'INPUT_DISABLED' since it won't detect input level changes that way (it's for ADC pins)
#define PINCTRL_DEFAULT (0) /* totem pole mode. trigger on 'both' */
#define PINCTRL_INPUT_PULLUP (_BV(4) | _BV(3)) /* input pullup mode */
#define PINCTRL_AND_PULLUP (_BV(5) | _BV(4) | _BV(3)) /* 'wired and' input pullup mode */
/* onboard LED is used to indicate, that the bootloader was entered (3x flashing) */
/* if monitor functions are included, LED goes on after monitor was entered */
// see also: hardware/arduino/variants/standard/pins_arduino.h
//
#ifdef LED_BUILTIN_PORT
#define LED_DDR ((&(LED_BUILTIN_PORT))->DIR)
// NOTE: if I don't cast the address as 'volatile uint8_t *' some processors won't work properly
#define LED_PORT (*((volatile uint8_t *) &((&(LED_BUILTIN_PORT))->OUT) ))
#define LED_PIN (*((volatile uint8_t *) &((&(LED_BUILTIN_PORT))->IN) ))
#define LED_CTRL (*((volatile uint8_t *) &(*(&((&(LED_BUILTIN_PORT))->PIN0CTRL) + LED_BUILTIN_PIN)) ))
#define LED_PIN_BIT _BV(LED_BUILTIN_PIN)
#define LED_INTCTRL (*((volatile uint8_t *) &((&(LED_BUILTIN_PORT))->INTCTRL) ))
#else // LED_BUILTIN_PORT
// LED on PR1
#define LED_DDR PORTR_DIR /* D manual section 11.12.1 */
#define LED_PORT PORTR_OUT /* D manual section 11.12.5 */
#define LED_PIN PORTR_IN /* D manual section 11.12.9 */
#define LED_CTRL PORTR_PIN1CTRL /* D manual section 11.12.15 */
#define LED_PIN_BIT _BV(1)
#define LED_INTCTRL PORTR_INTCTRL
#endif // LED_BUILTIN_PORT
// SERIAL PORT AND REMAP REGISTER
#ifdef PORTC_REMAP /* does it exist? */
#define SERIAL_PORT_REMAP_REG ((&(SERIAL_PORT))->REMAP)
#endif // PORTC_REMAP
#ifdef USARTC0_CTRLD
#define SERIAL_USART_CTRLD (*((volatile uint8_t *) &((&(SERIAL_USART))->CTRLD) ))
#endif // USARTC0_CTRLD
#if 0
// legacy testing code, currently commented out
// NOTE: if I don't cast the address as 'volatile uint8_t *' some processors won't work properly
#define SERIAL_PORT_PIN2CTRL (*((volatile uint8_t *) &((&(SERIAL_PORT))->PIN2CTRL) ))
#define SERIAL_PORT_PIN3CTRL (*((volatile uint8_t *) &((&(SERIAL_PORT))->PIN3CTRL) ))
#define SERIAL_PORT_PIN6CTRL (*((volatile uint8_t *) &((&(SERIAL_PORT))->PIN6CTRL) ))
#define SERIAL_PORT_PIN7CTRL (*((volatile uint8_t *) &((&(SERIAL_PORT))->PIN7CTRL) ))
#define SERIAL_PORT_OUT (*((volatile uint8_t *) &((&(SERIAL_PORT))->OUT) ))
#define SERIAL_PORT_DIR (*((volatile uint8_t *) &((&(SERIAL_PORT))->DIR) ))
#define SERIAL_USART_STATUS (*((volatile uint8_t *) &((&(SERIAL_USART))->STATUS) ))
#define SERIAL_USART_DATA (*((volatile uint8_t *) &((&(SERIAL_USART))->DATA) ))
#define SERIAL_USART_CTRLA (*((volatile uint8_t *) &((&(SERIAL_USART))->CTRLA) ))
#define SERIAL_USART_CTRLB (*((volatile uint8_t *) &((&(SERIAL_USART))->CTRLB) ))
#define SERIAL_USART_CTRLC (*((volatile uint8_t *) &((&(SERIAL_USART))->CTRLC) ))
#define SERIAL_USART_BAUDCTRLA (*((volatile uint8_t *) &((&(SERIAL_USART))->BAUDCTRLA) ))
#define SERIAL_USART_BAUDCTRLB (*((volatile uint8_t *) &((&(SERIAL_USART))->BAUDCTRLB) ))
#else
#define SERIAL_PORT_PIN2CTRL PORTD_PIN2CTRL
#define SERIAL_PORT_PIN3CTRL PORTD_PIN3CTRL
#define SERIAL_PORT_PIN6CTRL PORTD_PIN6CTRL
#define SERIAL_PORT_PIN7CTRL PORTD_PIN7CTRL
#define SERIAL_PORT_DIR PORTD_DIR
#define SERIAL_PORT_OUT PORTD_OUT
#define SERIAL_USART_STATUS USARTD0_STATUS
#define SERIAL_USART_DATA USARTD0_DATA
#define SERIAL_USART_CTRLA USARTD0_CTRLA
#define SERIAL_USART_CTRLB USARTD0_CTRLB
#define SERIAL_USART_CTRLC USARTD0_CTRLC
#define SERIAL_USART_BAUDCTRLA USARTD0_BAUDCTRLA
#define SERIAL_USART_BAUDCTRLB USARTD0_BAUDCTRLB
#endif
// THIS SECTION LEFT FOR FUTURE REFERENCE - do we want 'monitor' functions on the xmega?
///* monitor functions will only be compiled when using ATmega128, due to bootblock size constraints */
//#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__)
//#define MONITOR 1
//#endif
/* define various device id's */
/* manufacturer byte is always the same */
// DEFAULT SIGNATURES (for now, hard-coded for the CPU, later use -D)
//#define SIG1 0x1E // Yep, Atmel is the only manufacturer of AVR micros. Single source :( [hey why is this a surprise? - BF]
//#define SIG2 0x95
//#define SIG3 0x4c /* this is the sig byte that the Arduino environment looks for */
#ifndef SIG1
#define SIG1 SIGNATURE_0 /* from the header file */
#endif // SIG1
#ifndef SIG2
#define SIG2 SIGNATURE_1
#endif // SIG2
#ifndef SIG3
#define SIG3 SIGNATURE_2
#endif // SIG3
#define SIGNATURE_BYTES ( ((unsigned long)SIG1 << 16) | ((unsigned long)SIG2 << 8) | (unsigned long)SIG3 )
// use APP_SECTION_PAGE_SIZE as-is instead
// use conditional so I can assign it with a '-D' in the compiler command
#ifndef PAGE_SIZE
#define PAGE_SIZE APP_SECTION_PAGE_SIZE
#endif // PAGE_SIZE
// OLD CODE FOR REFERENCE
//// NOTE that page size is expressed in WORDS, not bytes, so must divide byte size by 2
//#ifndef PAGE_SIZE
//#define PAGE_SIZE (APP_SECTION_PAGE_SIZE / 2) /*0x40U*/ /* 64 words (128 bytes) for the ATXMega32E5 - see sect 8.12 in the ATXMega32E5 (etc) manual */
//#endif // PAGE_SIZE
/* function prototypes */
void putch(char);
void putstr(unsigned char *pBuf, char nBytes);
void flush(void);
char getch(void);
void getNch(uint8_t);
void byte_response(uint8_t);
void nothing_response(void);
char gethex(void);
void puthex(char);
void soft_boot(void) __attribute__((noreturn));
char smart_delay_ms(uint16_t ms);
#ifdef USE_STK500V2
void flushin(void);
uint8_t do_getch_and_checksum(void);
void do_putch_and_checksum(uint8_t chPut);
#endif // USE_STK500V2
// DEBUG STUFF
//#define ENABLE_BANG /* for STK500v2, enable '!' command to test serial port */
/* some variables */
#if defined(USE_STK500V2) || defined(USE_CATERINA)
#if defined(RAMPZ)
typedef uint32_t address_t;
#else
typedef uint16_t address_t;
#endif
address_t address = 0;
static uint8_t checksum; // used by 'do_XXXch_and_checksum'
#else // USE_STK500V2
volatile union address_union
{
// the original 'Arduino' bootloader protocol defined it *this* way
#ifdef RAMPZ
uint32_t dword;
#endif // RAMPZ
uint16_t word;
#ifdef RAMPZ
uint8_t byte[4];
#else // RAMPZ
uint8_t byte[2];
#endif // RAMPZ
} address;
#endif // USE_STK500V2
volatile union length_union
{
uint16_t word;
uint8_t byte[2];
} length;
volatile struct flags_struct
{
unsigned eeprom : 1;
unsigned rampz : 1;
} flags;
#ifndef __AVR_XMEGA__
#error this is an xmega bootloader, you should only use it for XMEGA
#endif // __AVR_XMEGA__
#if defined(USE_STK500V2) || defined(USE_CATERINA)
#if PAGE_SIZE < 256
static unsigned char msgBuffer[288]; // the stk500boot.c defined it as 285
#else // PAGE_SIZE >= 256
static unsigned char msgBuffer[PAGE_SIZE + 32]; // 32 extra bytes
#endif // PAGE_SIZE <, >= 256
// other vars used solely for STK500V2
static unsigned char seqNum;// = 0;
static unsigned int msgLength;// = 0;
#else // USE_STK500V2
// use PAGE_SIZE for buffer size - usually assigned to APP_SECTION_PAGE_SIZE
#if PAGE_SIZE < 256
uint8_t buff[258]; // min size
#else // PAGE_SIZE >= 256
uint8_t buff[PAGE_SIZE + 2]; // was 512 - largest page size 0x200 on XMEGA
#endif // PAGE SIZE <, >= 256
#endif // USE_STK500V2
uint8_t error_count;
uint8_t blink_mode;
/////////////////////////////////////////////////////////////////////////////////////////////////////
// APP START - different definitions for >64K NVRAM and <=64K
#if defined(EIND) && defined(__AVR_3_BYTE_PC__) // need to re-do the way we call the application
// basically this is a 3 byte 'retpoline' which is easier than doing it any other way
void app_start(void)
{
// first, assign 0 to EIND (I'm jumping to page 0, always)
__asm volatile ("ldi r24,0\n\t"
"out %i0,r24" :: "n" (&EIND) : "memory");
// next, push 3 zeros onto the stack and do a return (it's a 3-byte PC so this should work)
// I check for '__AVR_3_BYTE_PC__' earlier
__asm volatile ("ldi r30,0\n\t"
"push r30\n\t"
"push r30\n\t"
"push r30\n\t"
"ret\r\n" ::: "memory");
// NOTE: the ret address for the function that called THIS one should be ok to have on the stack
}
// NOTE: this is in main.c now, in the core
//// for info on THIS thing, see http://gcc.gnu.org/onlinedocs/gcc/AVR-Options.html
//static void __attribute__((section(".init3"),naked,used,no_instrument_function)) init3_set_eind (void)
//{
// __asm volatile ("ldi r24,pm_hh8(__trampolines_start)\n\t"
// "out %i0,r24" :: "n" (&EIND) : "r24","memory");
//}
#else // no EIND or 3-byte PC, we're fine
// when I don't have a 3-byte program counter, I can safely call via a function pointer
void (*app_start)(void) = 0x0000; // here it's a function pointer with an address of 0000H
#endif // EIND+3-byte PC vs "not that"
/////////////////////////////////////////////////////////////////////////////////////////////////////
// implementation-specific utilities
#ifdef USE_CATERINA
// this was derived from a message board post. The function is public to make it easy to
// use the 'Production Signature Row'. There is a unique identifier for the CPU as well as
// calibration data for the ADC available, and also USB settings (for USB-capable devices)
// See sect. 4.14 "Production Signature Row" in 'D' manual.
uint8_t readCalibrationData(uint16_t iIndex)
{
uint8_t rVal;
/* Load the NVM Command register to read the calibration row. */
NVM_CMD = NVM_CMD_READ_CALIB_ROW_gc; // see the section on NVM operations and lpm instruction
// rVal = pgm_read_byte_near(iIndex); // effectively the same thing as the inline assembler
__asm__ ("lpm %0, Z\n" : "=r" (rVal) : "z" (iIndex)); // do it THIS way instead
/* Clean up NVM Command register. */
NVM_CMD = NVM_CMD_NO_OPERATION_gc;
return(rVal);
}
#endif // USE_CATERINA
////////////////////////////////////////////
// _ ____ //
// _ __ ___ __ _ (_) _ __ / /\ \ //
// | '_ ` _ \ / _` || || '_ \ | | | | //
// | | | | | || (_| || || | | || | | | //
// |_| |_| |_| \__,_||_||_| |_|| | | | //
// \_\/_/ //
////////////////////////////////////////////
/* main program starts here */
int main(void)
{
uint8_t ch, ch2, bod;
register uint8_t bootflags;
uint16_t w1;
uint8_t firstchar;
#if defined(USE_STK500V2) || defined(USE_CATERINA)
unsigned char *p1;
#endif // USE_STK500V2
//#if defined(WATCHDOG_MODS) ALWAYS, now
// TODO: create a stack frame? some CPUs may not do this right, from what I have seen
if(SPL != (uint8_t)((INTERNAL_SRAM_START + INTERNAL_SRAM_SIZE) & 0xff) ||
SPH != (uint8_t)(((INTERNAL_SRAM_START + INTERNAL_SRAM_SIZE) >> 8) & 0xff))
{
// TODO: I need to set the stack up...
}
// this part needs to be done right away
bootflags = RST_STATUS & 0x3f; // bits 6 and 7 aren't used according to the manual (note bit 6 is defined as RST_SDRF_bm in nearly every header)
#ifdef RST_SDRF_bm
RST_STATUS = 0x7f; // clear bit 6 also
#else // RST_SDRF_bm
RST_STATUS = 0x3f; // write 1 bits to clear everything (so I don't loop)
#endif // RST_SDRF_bm
// --------------------------
// disable watchdog timer NOW
// --------------------------
CCP = CCP_IOREG_gc; // 0xd8 - see D manual, sect 3.14.1 (protected I/O)
WDT_CTRL = WDT_CEN_bm; // sets watchdog timer "enable" bit to zero - bit 0 must be set to change bit 1 - section 9.7.1
CCP = CCP_IOREG_gc; // 0xd8 - see D manual, sect 3.14.1 (protected I/O)
WDT_WINCTRL = WDT_WCEN_bm; // sets watchdog 'window' timer "enable" bit to zero - bit 0 must be set to change bit 1 - section 9.7.2
// the 'bootflags' value will be non-zero if I did a normal reboot, or had the WDT time
// out, or had a brownout, or soft reboot, or hard reboot. But if I merely jump here,
// it's going to be zero, so I'll execute a soft reboot to make sure I'm not boot-looping
// due to jumping into erased NVRAM and executing NOP instructions until I get here.
// (that generally doesn't work very well since the hardware doesn't properly reset)
if(!bootflags) // if 'bootflags' is zero, I executed this directly. So to prevent boot-loops after a bad flash,
{ // I'll force a 'soft boot' which re-enters the bootloader normally, preventing a boot-loop
soft_boot();
}
// NOW assign 'ch' to the watchdog bit (3) and bod to the B.O.D. bit (2)
// TODO: other flags? I might want to do a soft boot into a special feature, like bootloader flashing
ch = bootflags & RST_WDRF_bm /*_BV(3)*/; // watchdog bit, D manual sect 8.5.1
bod = bootflags & RST_BORF_bm /*_BV(2)*/; // brown out detector (8.5.1)
// TODO: add other "skip the bootloader flash check" flags to this? like soft boot?
// if I soft boot here, it might be an INTERNAL call to 'soft_boot' so another
// method will be needed to detect 'boot directly into the flash code'.
// NOTE: one candidate is a special EEPROM memory location, assigned to 'a function'
// this would deal with watchdog timers as well as soft booting into the bootloader
// to do something specific like writing the NVRAM.
// ----------------------------
// HANDLING BROWN-OUT DETECTION
// ----------------------------
// TODO: special brown-out detect code
// NEXT, set up the interrupt controller to disable interrupts
// Important. See 10.8.3 in D manual. The startup code will need
// to re-enable them in the application section for 'app IVT.
CCP = CCP_IOREG_gc; // 0xd8 - see D manual, sect 3.14.1 (protected I/O)
PMIC_CTRL = 0xc0; // binary 11000000 all 3 int levels disabled, round-robin enabled, IVT starts at 10002H
if(bod)
{
// do something special if brown-out detected, like keeping the clock slow
// goto skip_clock; // if I did the B.O.D. skip the clock stuff (this is a battery system strategy)
}
// -------------------------------------------------
// The CLOCK section (all xmegas need this, really)
// -------------------------------------------------
// enable BOTH the 32Mhz and 32.768KHz internal clocks [ignore what else might be set for now]
// sect 6.10.1 - enable 32.768KHz _BV(2), 32Mhz _BV(1). 2Mhz is _BV(0)
// _BV(3) and _BV(4) are for PLL and external - will set to 0 later
OSC_CTRL |= OSC_RC32KEN_bm | OSC_RC32MEN_bm; // enable 32khz osc, 32mhz osc - 'D4' manual sect 6.10.1
if(!(CLK_LOCK & CLK_LOCK_bm)) // clock lock bit NOT set, so I can muck with the clock
{ // note that in the bootloader this should NEVER happen. check anyway.
if((CLK_CTRL & CLK_SCLKSEL_gm) != CLK_SCLKSEL_RC32M_gc) // it's not already 32 Mhz (D manual 6.9.1)
{
// wait until 32mhz clock is 'stable'
for(w1=32767; w1 > 0; w1--) // TODO: remove counter?
{
// spin on oscillator status bit for 32Mhz oscillator
if(OSC_STATUS & OSC_RC32MRDY_bm) // 32Mhz oscillator is 'ready' (6.10.2)
{
break;
}
}
// for now, I can allow the clock to NOT be changed if it's
// not ready. This prevents infinite loop inside startup code
if(!(OSC_STATUS & OSC_RC32MRDY_bm)) // is my oscillator 'ready' ?
{
goto skip_clock; // exit - don't change anything
}
// switch to 32Mhz clock using internal source
CCP = CCP_IOREG_gc; // 0xd8 - see D manual, sect 3.14.1 (protected I/O)
CLK_CTRL = CLK_SCLKSEL_RC32M_gc; // set the clock to 32Mhz (6.9.1)
}
if(CLK_PSCTRL != 0)
{
CCP = CCP_IOREG_gc; // 0xd8 - see D manual, sect 3.14.1 (protected I/O)
CLK_PSCTRL = CLK_PSADIV_1_gc | CLK_PSBCDIV_1_1_gc; // set the clock divider(s) to 1:1 (6.9.2)
}
// now that I've changed the clock, disable 2Mhz, PLL, and external clocks
// 32.768KHz should remain active, but I need to make sure it's stable
// sect 6.10.1 - disable PLL, external, 2Mhz clocks
OSC_CTRL &= ~(OSC_PLLEN_bm | OSC_XOSCEN_bm // exclude OSC_RC2MEN_bm (don't disable 2M oscillator in bootloader)
#ifdef OSC_RC8MCAL // only present in 'E' series
| OSC_RC8MEN_bm /* disables 8Mhz oscillator */
#endif // OSC_RC8MCAL
);
// wait until 32.768KHz clock is 'stable'. this one goes for a while
// in case it doesn't stabilize in a reasonable time. I figure about
// 64*255 clock cycles should be enough, ya think?
for(w1=65535; w1 > 0; w1--)
{
for(ch2=255; ch2 > 0; ch2--) // this waits up to 256 times longer than just the outer loop
{
if(OSC_STATUS & OSC_RC32KRDY_bm) // 32.768KHz oscillator is 'ready' (6.10.2)
{
goto done_waiting_for_osc_status;
}
}
}
done_waiting_for_osc_status: // at this point the 32.768khz oscillator should be stable enough for the DFLL
// enable DFLL auto-calibration of the 32Mhz internal oscillator
// (it uses the reasonably precise 32.768KHz clock to do it)
// This is the BEST clock strategy to use for 32Mhz.
#ifdef OSC_RC32MCREF_gm /* if this is present, the enum for OSC_RC32MCREF_enum is also present */
OSC_DFLLCTRL = OSC_RC32MCREF_RC32K_gc; // sect 6.10.7 - select 32.768KHz osc for everything, basically
// use the enumeration/constant if it's present
#else // OSC_RC32MCREF_gm not present
OSC_DFLLCTRL = 0; // sect 6.10.7 - select 32.768KHz osc for everything, basically
// for header files that do not have the enumeration/constant defined, this will have to do
#endif // OSC_RC32MCREF_gm
DFLLRC32M_CTRL = DFLL_ENABLE_bm; // set the bit to enable DFLL calibration - section 6.11.1
// NOTE: for Caterina (USB) it is important to have a calibrated clock
#ifdef USE_CATERINA
#ifndef CLK_USBEN_bm
#define CLK_USBEN_bm CLK_USBSEN_bm /* name change of definition from previous header */
#endif // CLK_USBEN_bm
// caterina bootloader needs to set up the USB clock, which will take a few
// extra things to set up.
USB_CTRLA = 0; // shut down USB (should already be, but make sure)
USB_CTRLB = 0; // detach D- and D+
CLK_USBCTRL = 0; // shut off USB clock - section 7.9.5 in AU manual
OSC_CTRL &= ~(OSC_PLLEN_bm); // disable PLL osc - section 7.9.1 in AU manual
// 32Mhz (divided by 4, so it's 8Mhz) as the source
// multiplication factor of 6 - result = 48Mhz
OSC_PLLCTRL = OSC_PLLSRC_RC32M_gc | 6; // 6 times the 8Mhz frequency - section 7.10.6 in AU manual
OSC_CTRL |= OSC_PLLEN_bm; // re-enable PLL - section 7.9.5 in AU manual
while(!(OSC_STATUS & OSC_PLLRDY_bm)) // wait for PLL to be 'ready'
{
// TODO: timeout? I need to wait until it's stable
}
#ifdef USB_FAST
CLK_USBCTRL = CLK_USBSRC_PLL_gc; // use PLL (divide by 1, no division) - section 7.9.5 in AU manual
#else // USB_FAST
CLK_USBCTRL = CLK_USBSRC_PLL_gc // use PLL - section 7.9.5 in AU manual
| CLK_USBPSDIV_8_gc; // divide by 8 for 6mhz operation (12Mhz? see 7.3.6 which says 12Mhz or 48Mhz)
#endif // USB_FAST
CLK_USBCTRL |= CLK_USBEN_bm; // enable bit - section 7.9.5 in AU manual
// assign CAL register from product signatures (4.17.17,18)
USB_CAL0 = readCalibrationData((uint8_t)(uint16_t)&PRODSIGNATURES_USBCAL0); // docs say 'CALL'
USB_CAL1 = readCalibrationData((uint8_t)(uint16_t)&PRODSIGNATURES_USBCAL1); // docs say 'CALH'
// at this point the USB clock is running with USB disabled.
// For the rest of the potential startup code on the USB, not clock related,
// see USBCore.cpp, 'USBDevice_::attach()'
//#ifdef USB_FAST
// USB_CTRLA = MAXEP // max # of endpoints minus 1 - section 20.14.1 in AU manual
// | USB_SPEED_bm // FAST USB - all ahead 'FULL' - aka 'FULL' speed ahead! - ok bad PUNishment
// | USB_STFRNUM_bm; // store the frame number (mostly for debugging)
//#else // USB_FAST
// USB_CTRLA = MAXEP // max # of endpoints minus 1 - section 20.14.1 in AU manual
// | USB_STFRNUM_bm; // store the frame number (mostly for debugging)
//#endif // USB_FAST
#endif // USE_CATERINA
}
// I'll be using the 1.024khz clock (from the 32.768KHz clock) for the real-time counter
// this will give me a reasonable "about 1 millisecond" accuracy on the RTC
// NOTE: I may not have checked for this if I skipped the previous section,
// so now I check again, just in case, to make sure the 32.768KHz osc is stable
for(w1=65535; w1 > 0; w1--)
{
for(ch2=255; ch2 > 0; ch2--)
{
if(OSC_STATUS & OSC_RC32KRDY_bm) // 32.768KHz oscillator is 'ready' (6.10.2)
{
goto done_waiting_again_osc_status;
}
}
}
done_waiting_again_osc_status:
if(!(OSC_STATUS & OSC_RC32KRDY_bm)) // is my oscillator 'ready' ?
{
goto skip_clock; // exit - don't change anything else
}
// RUN-TIME clock - use internal 1.024 khz source. 32khz needed for this
// (the run-time clock works pretty well this way, scheduling events, CPU wakeup, etc.)
// CLK_RTCCTRL = CLK_RTCSRC_RCOSC_gc/*was 2, was wrong*/; // section 6.9.4, 7.9.4 in A[U] manual
CLK_RTCCTRL = 2; // anything else and it won't boot up
skip_clock: // go here if clock cannot be assigned for some reason or is already assigned
// regular 'WATCHDOG_MODS' code starts back up here (NOTE: 'WATCHDOG_MODS' are always active now)
// Check if the WDT was used to reset, in which case we don't bootload and skip straight to the code. w00t.
if(ch) // if it's not an external reset... (in this case, JUST checking for watchdog, later BOD as well?)
{
app_start(); // skip bootloader (NOTE: function call WAY smaller than goto)
}
/* check if flash is programmed already, if not start bootloader anyway */
if(pgm_read_byte_near(0x0000) != 0xFF)
{
// TODO: handle differently if programmed?
}
#ifndef USE_CATERINA
//------------------------------
// UARTD0 config using HIGH pins
//------------------------------
// make sure that the HIGH pins are configured for the USART
#ifdef SERIAL_PORT_REMAP
// TODO: allow this to be used for the A1 series with SERIAL1 ?
#ifdef SERIAL_PORT_REMAP_REG
SERIAL_PORT_REMAP_REG = PORT_USART0_bm; // see 12.13.13 in 'E' manual
#endif // SERIAL_PORT_REMAP_REG
// PD6 (GPIO 6) must have input pullup resistor (for serial I/O)
SERIAL_PORT_PIN6CTRL = PINCTRL_INPUT_PULLUP;
SERIAL_PORT_OUT |= _BV(6);
SERIAL_PORT_DIR &= ~_BV(6);
// PD7 (GPIO 7) must be configured as an output
SERIAL_PORT_PIN7CTRL = PINCTRL_DEFAULT;
SERIAL_PORT_OUT |= _BV(7);
SERIAL_PORT_DIR |= _BV(7);
#else // REMAP
#ifdef SERIAL_PORT_REMAP_REG
SERIAL_PORT_REMAP_REG = 0; // see 12.13.13 in 'E' manual
#endif // SERIAL_PORT_REMAP_REG
// PD2 (GPIO 2) must have input pullup resistor (for serial I/O)
SERIAL_PORT_PIN2CTRL = PINCTRL_INPUT_PULLUP;
SERIAL_PORT_OUT |= _BV(2);
SERIAL_PORT_DIR &= ~_BV(2);
// PD7 (GPIO 7) must be configured as an output
SERIAL_PORT_PIN3CTRL = PINCTRL_DEFAULT;
SERIAL_PORT_OUT |= _BV(3);
SERIAL_PORT_DIR |= _BV(3);
#endif // REMAP
/////////////////////////////////////////////////////////////////////
// ____ _ _ ____ _ //
// / ___| ___ _ __ (_) __ _ | | | __ ) __ _ _ _ __| | //
// \___ \ / _ \| '__|| | / _` || | | _ \ / _` || | | | / _` | //
// ___) || __/| | | || (_| || | | |_) || (_| || |_| || (_| | //
// |____/ \___||_| |_| \__,_||_| |____/ \__,_| \__,_| \__,_| //
// //
/////////////////////////////////////////////////////////////////////
// set the CORRECT baud rate NOW. normally just use 115k baud
#if BAUD_RATE == 115200
// section 19.4.4 - 'double speed' flag
// since this is set below, maybe it's not needed here?
#ifdef DOUBLE_SPEED
#define BAUD_SETTING ((-2 << 12) | 135)
// // section 19.4.4
// SERIAL_USART_CTRLB = USART_CLK2X_bm/*_BV(2)*/; // enable clock 2x (everything else disabled)
#else // DOUBLE_SPEED
#define BAUD_SETTING ((-3 << 12) | 131)
// SERIAL_USART_CTRLB = 0; // DISable clock 2x
#endif // DOUBLE_SPEED
#else // BAUD_RATE != 115200
// section 19.4.4 - 'double speed' flag
// since this is set below, maybe it's not needed here?
#ifdef DOUBLE_SPEED
// // section 19.4.4
// SERIAL_USART_CTRLB = USART_CLK2X_bm/*_BV(2)*/; // enable clock 2x (everything else disabled)
#else // DOUBLE_SPEED
// SERIAL_USART_CTRLB = 0; // DISable clock 2x
#endif // DOUBLE_SPEED
// for now only 115k supported, so it's an error if I try to compile this for different baud rates
#error baud rate BAUD_RATE is NOT supported (for now)
#endif // BAUD_RATE == 115200
// assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
SERIAL_USART_BAUDCTRLA = ((uint8_t)BAUD_SETTING) & 0xff;
SERIAL_USART_BAUDCTRLB = (uint8_t)(BAUD_SETTING >> 8);
// CTRLA settings - no interrupts
SERIAL_USART_CTRLA = 0; // NO! SERIAL! PORT! INTERRUPTS!
// section 19.14.5 - USART mode, parity, bits
// CMODE 7:6 = 00 [async] PMODE 5:4 = 00 [none] SBMODE 3 = 0 [1 bit] CHSIZE 2:0 = 3 (8-bit)
SERIAL_USART_CTRLC = USART_CHSIZE_8BIT_gc; // SERIAL_8N1 - see HardwareSerial.h
#ifdef USARTD0_CTRLD // which means we have a CTRLD - E5's do
SERIAL_USART_CTRLD = 0; // always set to zero (E5 special)
#endif // USARTD0_CTRLD
// last of all, assign CTRLB which switches on the right pins
#ifdef USE_STK500V2
__builtin_avr_delay_cycles(F_CPU / 200); // delay approximately 5 msec before enabling serial port for STK500V2
// this is to allow things to settle a bit beforehand
#elif defined(USE_CATERINA)
#warning - do I need to do the up-front delay for caterina?
#endif // USE_STK500V2
////////////////////////////
// ENABLE THE SERIAL PORT //
////////////////////////////
// See 'D' manual section 19.4.4
#ifdef DOUBLE_SPEED
SERIAL_USART_CTRLB = USART_RXEN_bm | USART_TXEN_bm | USART_CLK2X_bm; // enable double-speed, RX, TX, and disable other stuff
#else // DOUBLE_SPEED
SERIAL_USART_CTRLB = USART_RXEN_bm | USART_TXEN_bm; // enable RX, TX, disable other stuff
#endif // DOUBLE_SPEED
#endif // !USE_CATERINA
// before globally enabling interrupts, make sure that 'certain hardware' isn't possibly messing things up
// This is especially true for non-USB boot when USB support is in the CPU+peripherals
#ifdef USB_INTCTRLA
USB_INTCTRLA = 0;
USB_INTCTRLB = 0;
#endif // USB_INTCTRLA
///////////////////////////////////////////////////////////////
// _____ _ _ ___ _ //
// | ____| _ __ __ _ | |__ | | ___ |_ _| _ __ | |_ //
// | _| | '_ \ / _` || '_ \ | | / _ \ | | | '_ \ | __| //
// | |___ | | | || (_| || |_) || || __/ | | | | | || |_ //
// |_____||_| |_| \__,_||_.__/ |_| \___| |___||_| |_| \__| //
// //
///////////////////////////////////////////////////////////////
sei(); // ok to globally enable interrupts now
// assign pin mode to LED output pin
LED_CTRL = PINCTRL_DEFAULT;
LED_DDR |= LED_PIN_BIT;
/* flash onboard LED to signal entering of bootloader */
#if NUM_LED_FLASHES == 0
ch2 = 6; //3;
#else
ch2 = NUM_LED_FLASHES << 1;
#endif // NUM_LED_FLASHES
// NOTE: call to 'getch' turns off the LED
firstchar = 0; // to make sure we don't start the app by accident
// detect whether the first character is being received or not
// and before anything else, zero out the error counter
error_count = 0;
// ----------------
// BLINK MODE SETUP
// ----------------
blink_mode = ch2; // this causes 'getch' to do the blinking
LED_PORT |= LED_PIN_BIT; // turn on the LED to indicate receiving data
/* forever loop */
for (;;)
{
#if !defined(USE_STK500V2) && !defined(USE_CATERINA)
/* get character from UART */
ch = getch();
// ------------------------------------