Project

General

Profile

Statistics
| Branch: | Revision:

root / arduino-1.0 / hardware / arduino / bootloaders / bt / ATmegaBOOT_168.c @ 58d82c77

History | View | Annotate | Download (26.1 KB)

1 58d82c77 Tom Mullins
/**********************************************************/
2
/* Serial Bootloader for Atmel megaAVR Controllers        */
3
/*                                                        */
4
/* tested with ATmega8, ATmega128 and ATmega168           */
5
/* should work with other mega's, see code for details    */
6
/*                                                        */
7
/* ATmegaBOOT.c                                           */
8
/*                                                        */
9
/* build: 050815                                          */
10
/* date : 15.08.2005                                      */
11
/*                                                        */
12
/* 20060802: hacked for Arduino by D. Cuartielles         */
13
/*           based on a previous hack by D. Mellis        */
14
/*           and D. Cuartielles                           */
15
/*                                                        */
16
/* Monitor and debug functions were added to the original */
17
/* code by Dr. Erik Lins, chip45.com. (See below)         */
18
/*                                                        */
19
/* Thanks to Karl Pitrich for fixing a bootloader pin     */
20
/* problem and more informative LED blinking!             */
21
/*                                                        */
22
/* For the latest version see:                            */
23
/* http://www.chip45.com/                                 */
24
/*                                                        */
25
/* ------------------------------------------------------ */
26
/*                                                        */
27
/* based on stk500boot.c                                  */
28
/* Copyright (c) 2003, Jason P. Kyle                      */
29
/* All rights reserved.                                   */
30
/* see avr1.org for original file and information         */
31
/*                                                        */
32
/* This program is free software; you can redistribute it */
33
/* and/or modify it under the terms of the GNU General    */
34
/* Public License as published by the Free Software       */
35
/* Foundation; either version 2 of the License, or        */
36
/* (at your option) any later version.                    */
37
/*                                                        */
38
/* This program is distributed in the hope that it will   */
39
/* be useful, but WITHOUT ANY WARRANTY; without even the  */
40
/* implied warranty of MERCHANTABILITY or FITNESS FOR A   */
41
/* PARTICULAR PURPOSE.  See the GNU General Public        */
42
/* License for more details.                              */
43
/*                                                        */
44
/* You should have received a copy of the GNU General     */
45
/* Public License along with this program; if not, write  */
46
/* to the Free Software Foundation, Inc.,                 */
47
/* 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA */
48
/*                                                        */
49
/* Licence can be viewed at                               */
50
/* http://www.fsf.org/licenses/gpl.txt                    */
51
/*                                                        */
52
/* Target = Atmel AVR m128,m64,m32,m16,m8,m162,m163,m169, */
53
/* m8515,m8535. ATmega161 has a very small boot block so  */
54
/* isn't supported.                                       */
55
/*                                                        */
56
/* Tested with m128,m8,m163 - feel free to let me know    */
57
/* how/if it works for you.                               */
58
/*                                                        */
59
/**********************************************************/
60
61
62
/* some includes */
63
#include <inttypes.h>
64
#include <avr/io.h>
65
#include <avr/pgmspace.h>
66
#include <avr/interrupt.h>
67
#include <avr/wdt.h>               
68
69
70
#define set_output(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
71
#define set_input(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
72
73
74
#define high(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
75
#define low(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
76
77
78
79
80
/* the current avr-libc eeprom functions do not support the ATmega168 */
81
/* own eeprom write/read functions are used instead */
82
#if !defined(__AVR_ATmega168__) || !defined(__AVR_ATmega328P__)
83
#include <avr/eeprom.h>
84
#endif
85
86
/* define F_CPU according to AVR_FREQ set in Makefile */
87
/* Is there a better way to pass such a parameter from Makefile to source code ? */
88
89
#define F_CPU     16000000L
90
91
#include <util/delay.h> 
92
93
94
/* 20060803: hacked by DojoCorp */
95
/* set the waiting time for the bootloader */
96
#define MAX_TIME_COUNT (F_CPU>>1)
97
98
/* set the UART baud rate */
99
/* 20060803: hacked by DojoCorp */
100
#define BAUD_RATE   115200
101
102
103
/* SW_MAJOR and MINOR needs to be updated from time to time to avoid warning message from AVR Studio */
104
/* never allow AVR Studio to do an update !!!! */
105
#define HW_VER         0x02
106
#define SW_MAJOR 0x01
107
#define SW_MINOR 0x0f
108
109
110
/* Adjust to suit whatever pin your hardware uses to enter the bootloader */
111
/* ATmega128 has two UARTS so two pins are used to enter bootloader and select UART */
112
/* BL0... means UART0, BL1... means UART1 */
113
#ifdef __AVR_ATmega128__
114
#define BL_DDR  DDRF
115
#define BL_PORT PORTF
116
#define BL_PIN  PINF
117
#define BL0     PINF7
118
#define BL1     PINF6
119
#else
120
/* other ATmegas have only one UART, so only one pin is defined to enter bootloader */
121
#define BL_DDR  DDRD
122
#define BL_PORT PORTD
123
#define BL_PIN  PIND
124
#define BL      PIND6
125
#endif
126
127
128
/* onboard LED is used to indicate, that the bootloader was entered (3x flashing) */
129
/* if monitor functions are included, LED goes on after monitor was entered */
130
#ifdef __AVR_ATmega128__
131
/* Onboard LED is connected to pin PB7 (e.g. Crumb128, PROBOmega128, Savvy128) */
132
#define LED_DDR  DDRB
133
#define LED_PORT PORTB
134
#define LED_PIN  PINB
135
#define LED      PINB7
136
#else
137
/* Onboard LED is connected to pin PB2 (e.g. Crumb8, Crumb168) */
138
#define LED_DDR  DDRB
139
#define LED_PORT PORTB
140
#define LED_PIN  PINB
141
/* 20060803: hacked by DojoCorp, LED pin is B5 in Arduino */
142
/* #define LED      PINB2 */
143
#define LED      PINB5
144
#endif
145
146
147
/* monitor functions will only be compiled when using ATmega128, due to bootblock size constraints */
148
#ifdef __AVR_ATmega128__
149
#define MONITOR
150
#endif
151
152
153
/* define various device id's */
154
/* manufacturer byte is always the same */
155
#define SIG1        0x1E        // Yep, Atmel is the only manufacturer of AVR micros.  Single source :(
156
157
#if defined __AVR_ATmega128__
158
#define SIG2        0x97
159
#define SIG3        0x02
160
#define PAGE_SIZE        0x80U        //128 words
161
162
#elif defined __AVR_ATmega64__
163
#define SIG2        0x96
164
#define SIG3        0x02
165
#define PAGE_SIZE        0x80U        //128 words
166
167
#elif defined __AVR_ATmega32__
168
#define SIG2        0x95
169
#define SIG3        0x02
170
#define PAGE_SIZE        0x40U        //64 words
171
172
#elif defined __AVR_ATmega16__
173
#define SIG2        0x94
174
#define SIG3        0x03
175
#define PAGE_SIZE        0x40U        //64 words
176
177
#elif defined __AVR_ATmega8__
178
#define SIG2        0x93
179
#define SIG3        0x07
180
#define PAGE_SIZE        0x20U        //32 words
181
182
#elif defined __AVR_ATmega88__
183
#define SIG2        0x93
184
#define SIG3        0x0a
185
#define PAGE_SIZE        0x20U        //32 words
186
187
#elif defined __AVR_ATmega168__
188
#define SIG2        0x94
189
#define SIG3        0x06
190
#define PAGE_SIZE        0x40U        //64 words
191
192
#elif defined __AVR_ATmega328P__
193
#define SIG2        0x95
194
#define SIG3        0x0F
195
#define PAGE_SIZE        0x40U        //64 words
196
197
#elif defined __AVR_ATmega162__
198
#define SIG2        0x94
199
#define SIG3        0x04
200
#define PAGE_SIZE        0x40U        //64 words
201
202
#elif defined __AVR_ATmega163__
203
#define SIG2        0x94
204
#define SIG3        0x02
205
#define PAGE_SIZE        0x40U        //64 words
206
207
#elif defined __AVR_ATmega169__
208
#define SIG2        0x94
209
#define SIG3        0x05
210
#define PAGE_SIZE        0x40U        //64 words
211
212
#elif defined __AVR_ATmega8515__
213
#define SIG2        0x93
214
#define SIG3        0x06
215
#define PAGE_SIZE        0x20U        //32 words
216
217
#elif defined __AVR_ATmega8535__
218
#define SIG2        0x93
219
#define SIG3        0x08
220
#define PAGE_SIZE        0x20U        //32 words
221
#endif
222
223
224
/* function prototypes */
225
void putch(char);
226
char getch(void);
227
void getNch(uint8_t);
228
void byte_response(uint8_t);
229
void nothing_response(void);
230
char gethex(void);
231
void puthex(char);
232
void flash_led(uint8_t);
233
234
/* some variables */
235
union address_union {
236
    uint16_t word;
237
    uint8_t  byte[2];
238
} address;
239
240
union length_union {
241
    uint16_t word;
242
    uint8_t  byte[2];
243
} length;
244
245
struct flags_struct {
246
    unsigned eeprom : 1;
247
    unsigned rampz  : 1;
248
} flags;
249
250
uint8_t buff[256];
251
uint8_t address_high;
252
253
uint8_t pagesz=0x80;
254
255
uint8_t i;
256
uint8_t bootuart = 0;
257
258
void (*app_start)(void) = 0x0000;
259
260
261
/* main program starts here */
262
int main(void)
263
{
264
    uint8_t ch,ch2;
265
    uint16_t w;
266
267
    asm volatile("nop\n\t");
268
269
    /* set pin direction for bootloader pin and enable pullup */
270
    /* for ATmega128, two pins need to be initialized */
271
#ifdef __AVR_ATmega128__
272
    BL_DDR &= ~_BV(BL0);
273
    BL_DDR &= ~_BV(BL1);
274
    BL_PORT |= _BV(BL0);
275
    BL_PORT |= _BV(BL1);
276
#else
277
    BL_DDR &= ~_BV(BL);
278
    BL_PORT |= _BV(BL);
279
#endif
280
281
282
#ifdef __AVR_ATmega128__
283
    /* check which UART should be used for booting */
284
    if(bit_is_clear(BL_PIN, BL0)) {
285
      bootuart = 1;
286
    }
287
    else if(bit_is_clear(BL_PIN, BL1)) {
288
      bootuart = 2;
289
    }
290
#endif
291
292
    /* check if flash is programmed already, if not start bootloader anyway */
293
    if(pgm_read_byte_near(0x0000) != 0xFF) {
294
295
#ifdef __AVR_ATmega128__
296
        /* no UART was selected, start application */
297
        if(!bootuart) {
298
          app_start();
299
        }
300
#else
301
        /* check if bootloader pin is set low */
302
        /* we don't start this part neither for the m8, nor m168 */
303
        //if(bit_is_set(BL_PIN, BL)) {
304
    //      app_start();
305
    //    }
306
#endif
307
    }
308
309
#ifdef __AVR_ATmega128__    
310
    /* no bootuart was selected, default to uart 0 */
311
    if(!bootuart) {
312
      bootuart = 1;
313
    }
314
#endif
315
316
317
    /* initialize UART(s) depending on CPU defined */
318
#ifdef __AVR_ATmega128__
319
    if(bootuart == 1) {
320
        UBRR0L = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
321
        UBRR0H = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
322
        UCSR0A = 0x00;
323
        UCSR0C = 0x06;
324
        UCSR0B = _BV(TXEN0)|_BV(RXEN0);
325
    }
326
    if(bootuart == 2) {
327
        UBRR1L = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
328
        UBRR1H = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
329
        UCSR1A = 0x00;
330
        UCSR1C = 0x06;
331
        UCSR1B = _BV(TXEN1)|_BV(RXEN1);
332
    }
333
#elif defined __AVR_ATmega163__
334
    UBRR = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
335
    UBRRHI = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
336
    UCSRA = 0x00;
337
    UCSRB = _BV(TXEN)|_BV(RXEN);        
338
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
339
340
        UBRR0H = ((F_CPU / 16 + BAUD_RATE / 2) / BAUD_RATE - 1) >> 8;
341
        UBRR0L = ((F_CPU / 16 + BAUD_RATE / 2) / BAUD_RATE - 1);
342
343
344
    //UBRR0L = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
345
    //UBRR0H = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
346
    UCSR0B = (1<<RXEN0) | (1<<TXEN0);
347
    UCSR0C = (1<<UCSZ00) | (1<<UCSZ01);
348
#elif defined __AVR_ATmega8__
349
  /* m8 */
350
  UBRRH = (((F_CPU/BAUD_RATE)/16)-1)>>8;         // set baud rate
351
  UBRRL = (((F_CPU/BAUD_RATE)/16)-1);
352
  UCSRB = (1<<RXEN)|(1<<TXEN);  // enable Rx & Tx
353
  UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);  // config USART; 8N1
354
#else
355
    /* m16,m32,m169,m8515,m8535 */
356
    UBRRL = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
357
    UBRRH = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
358
    UCSRA = 0x00;
359
    UCSRC = 0x06;
360
    UCSRB = _BV(TXEN)|_BV(RXEN);
361
#endif
362
363
    /* set LED pin as output */
364
    LED_DDR |= _BV(LED);
365
              
366
367
     
368
      set_output(DDRD,PIND7);
369
          high(PORTD,PD7);    
370
          for (i = 0; i < 16; i++) {
371
                 
372
                        _delay_loop_2(0);
373
          }
374
        
375
        
376
          low(PORTD,PD7);
377
378
379
    /* flash onboard LED to signal entering of bootloader */
380
#ifdef __AVR_ATmega128__
381
    // 4x for UART0, 5x for UART1
382
    flash_led(3 + bootuart);
383
#else
384
    flash_led(3);
385
#endif
386
    
387
    /* 20050803: by DojoCorp, this is one of the parts provoking the
388
                 system to stop listening, cancelled from the original */
389
    //putch('\0');
390
        
391
392
   //message("SET BT PAGEMODE 3 2000 1");    
393
putch('S');
394
putch('E');
395
putch('T');
396
putch(' ');
397
putch('B');
398
putch('T');
399
putch(' ');
400
putch('P');
401
putch('A');
402
putch('G');
403
putch('E');
404
putch('M');
405
putch('O');
406
putch('D');
407
putch('E');
408
putch(' ');
409
putch('3');
410
putch(' ');
411
putch('2');
412
putch('0');
413
putch('0');
414
putch('0');
415
putch(' ');
416
putch('1');
417
putch(0x0D);
418
419
  
420
          //put_s("SET BT ROLE 0 f 7d00");  
421
        putch('S');
422
        putch('E');
423
        putch('T');
424
        putch(' ');
425
        putch('B');
426
        putch('T');
427
        putch(' ');
428
        putch('R');
429
        putch('O');
430
        putch('L');
431
        putch('E');
432
        putch(' ');
433
        putch('0');
434
        putch(' ');
435
        putch('f');
436
        putch(' ');
437
        putch('7');
438
        putch('d');
439
        putch('0');
440
        putch('0');
441
        putch(0x0D);
442
443
444
445
446
447
448
    /* forever loop */
449
    for (;;) {
450
451
        /* get character from UART */
452
        ch = getch();
453
454
        /* A bunch of if...else if... gives smaller code than switch...case ! */
455
456
        /* Hello is anyone home ? */ 
457
        if(ch=='0') {
458
            nothing_response();
459
        }
460
461
462
        /* Request programmer ID */
463
        /* Not using PROGMEM string due to boot block in m128 being beyond 64kB boundry  */
464
        /* Would need to selectively manipulate RAMPZ, and it's only 9 characters anyway so who cares.  */
465
        else if(ch=='1') {
466
            if (getch() == ' ') {
467
                putch(0x14);
468
                putch('A');
469
                putch('V');
470
                putch('R');
471
                putch(' ');
472
                putch('I');
473
                putch('S');
474
                putch('P');
475
                putch(0x10);
476
            }
477
        }
478
479
480
        /* AVR ISP/STK500 board commands  DON'T CARE so default nothing_response */
481
        else if(ch=='@') {
482
            ch2 = getch();
483
            if (ch2>0x85) getch();
484
            nothing_response();
485
        }
486
487
488
        /* AVR ISP/STK500 board requests */
489
        else if(ch=='A') {
490
            ch2 = getch();
491
            if(ch2==0x80) byte_response(HW_VER);                // Hardware version
492
            else if(ch2==0x81) byte_response(SW_MAJOR);        // Software major version
493
            else if(ch2==0x82) byte_response(SW_MINOR);        // Software minor version
494
            else if(ch2==0x98) byte_response(0x03);                // Unknown but seems to be required by avr studio 3.56
495
            else byte_response(0x00);                                // Covers various unnecessary responses we don't care about
496
        }
497
498
499
        /* Device Parameters  DON'T CARE, DEVICE IS FIXED  */
500
        else if(ch=='B') {
501
            getNch(20);
502
            nothing_response();
503
        }
504
505
506
        /* Parallel programming stuff  DON'T CARE  */
507
        else if(ch=='E') {
508
            getNch(5);
509
            nothing_response();
510
        }
511
512
513
        /* Enter programming mode  */
514
        else if(ch=='P') {
515
            nothing_response();
516
        }
517
518
519
        /* Leave programming mode  */
520
        else if(ch=='Q') {
521
            nothing_response();
522
        }
523
524
525
        /* Erase device, don't care as we will erase one page at a time anyway.  */
526
        else if(ch=='R') {
527
            nothing_response();
528
        }
529
530
531
        /* Set address, little endian. EEPROM in bytes, FLASH in words  */
532
        /* Perhaps extra address bytes may be added in future to support > 128kB FLASH.  */
533
        /* This might explain why little endian was used here, big endian used everywhere else.  */
534
        else if(ch=='U') {
535
            address.byte[0] = getch();
536
            address.byte[1] = getch();
537
            nothing_response();
538
        }
539
540
541
        /* Universal SPI programming command, disabled.  Would be used for fuses and lock bits.  */
542
        else if(ch=='V') {
543
            getNch(4);
544
            byte_response(0x00);
545
        }
546
547
548
        /* Write memory, length is big endian and is in bytes  */
549
        else if(ch=='d') {
550
            length.byte[1] = getch();
551
            length.byte[0] = getch();
552
            flags.eeprom = 0;
553
            if (getch() == 'E') flags.eeprom = 1;
554
            for (w=0;w<length.word;w++) {
555
                buff[w] = getch();                                // Store data in buffer, can't keep up with serial data stream whilst programming pages
556
            }
557
            if (getch() == ' ') {
558
                if (flags.eeprom) {                                //Write to EEPROM one byte at a time
559
                    for(w=0;w<length.word;w++) {
560
#if defined(__AVR_ATmega168__)  || defined(__AVR_ATmega328P__)
561
                        while(EECR & (1<<EEPE));
562
                        EEAR = (uint16_t)(void *)address.word;
563
                        EEDR = buff[w];
564
                        EECR |= (1<<EEMPE);
565
                        EECR |= (1<<EEPE);
566
#else
567
                        eeprom_write_byte((void *)address.word,buff[w]);
568
#endif
569
                        address.word++;
570
                    }                        
571
                }
572
                else {                                                //Write to FLASH one page at a time
573
                    if (address.byte[1]>127) address_high = 0x01;        //Only possible with m128, m256 will need 3rd address byte. FIXME
574
                    else address_high = 0x00;
575
#ifdef __AVR_ATmega128__
576
                    RAMPZ = address_high;
577
#endif
578
                    address.word = address.word << 1;                //address * 2 -> byte location
579
                    /* if ((length.byte[0] & 0x01) == 0x01) length.word++;        //Even up an odd number of bytes */
580
                    if ((length.byte[0] & 0x01)) length.word++;        //Even up an odd number of bytes
581
                    cli();                                        //Disable interrupts, just to be sure
582
                        // HACKME: EEPE used to be EEWE
583
                    while(bit_is_set(EECR,EEPE));                        //Wait for previous EEPROM writes to complete
584
                    asm volatile(
585
                                 "clr        r17                \n\t"        //page_word_count
586
                                 "lds        r30,address        \n\t"        //Address of FLASH location (in bytes)
587
                                 "lds        r31,address+1        \n\t"
588
                                 "ldi        r28,lo8(buff)        \n\t"        //Start of buffer array in RAM
589
                                 "ldi        r29,hi8(buff)        \n\t"
590
                                 "lds        r24,length        \n\t"        //Length of data to be written (in bytes)
591
                                 "lds        r25,length+1        \n\t"
592
                                 "length_loop:                \n\t"        //Main loop, repeat for number of words in block                                                                                                                  
593
                                 "cpi        r17,0x00        \n\t"        //If page_word_count=0 then erase page
594
                                 "brne        no_page_erase        \n\t"                                                 
595
                                 "wait_spm1:                \n\t"
596
                                 "lds        r16,%0                \n\t"        //Wait for previous spm to complete
597
                                 "andi        r16,1           \n\t"
598
                                 "cpi        r16,1           \n\t"
599
                                 "breq        wait_spm1       \n\t"
600
                                 "ldi        r16,0x03        \n\t"        //Erase page pointed to by Z
601
                                 "sts        %0,r16                \n\t"
602
                                 "spm                        \n\t"                                                         
603
#ifdef __AVR_ATmega163__
604
                                 ".word 0xFFFF                \n\t"
605
                                 "nop                        \n\t"
606
#endif
607
                                 "wait_spm2:                \n\t"
608
                                 "lds        r16,%0                \n\t"        //Wait for previous spm to complete
609
                                 "andi        r16,1           \n\t"
610
                                 "cpi        r16,1           \n\t"
611
                                 "breq        wait_spm2       \n\t"                                                                         
612
613
                                 "ldi        r16,0x11        \n\t"        //Re-enable RWW section
614
                                 "sts        %0,r16                \n\t"                                                                          
615
                                 "spm                        \n\t"
616
#ifdef __AVR_ATmega163__
617
                                 ".word 0xFFFF                \n\t"
618
                                 "nop                        \n\t"
619
#endif
620
                                 "no_page_erase:                \n\t"                                                         
621
                                 "ld        r0,Y+                \n\t"        //Write 2 bytes into page buffer
622
                                 "ld        r1,Y+                \n\t"                                                         
623
                                                         
624
                                 "wait_spm3:                \n\t"
625
                                 "lds        r16,%0                \n\t"        //Wait for previous spm to complete
626
                                 "andi        r16,1           \n\t"
627
                                 "cpi        r16,1           \n\t"
628
                                 "breq        wait_spm3       \n\t"
629
                                 "ldi        r16,0x01        \n\t"        //Load r0,r1 into FLASH page buffer
630
                                 "sts        %0,r16                \n\t"
631
                                 "spm                        \n\t"
632
                                                         
633
                                 "inc        r17                \n\t"        //page_word_count++
634
                                 "cpi r17,%1                \n\t"
635
                                 "brlo        same_page        \n\t"        //Still same page in FLASH
636
                                 "write_page:                \n\t"
637
                                 "clr        r17                \n\t"        //New page, write current one first
638
                                 "wait_spm4:                \n\t"
639
                                 "lds        r16,%0                \n\t"        //Wait for previous spm to complete
640
                                 "andi        r16,1           \n\t"
641
                                 "cpi        r16,1           \n\t"
642
                                 "breq        wait_spm4       \n\t"
643
#ifdef __AVR_ATmega163__
644
                                 "andi        r30,0x80        \n\t"        // m163 requires Z6:Z1 to be zero during page write
645
#endif                                                                                                                  
646
                                 "ldi        r16,0x05        \n\t"        //Write page pointed to by Z
647
                                 "sts        %0,r16                \n\t"
648
                                 "spm                        \n\t"
649
#ifdef __AVR_ATmega163__
650
                                 ".word 0xFFFF                \n\t"
651
                                 "nop                        \n\t"
652
                                 "ori        r30,0x7E        \n\t"        // recover Z6:Z1 state after page write (had to be zero during write)
653
#endif
654
                                 "wait_spm5:                \n\t"
655
                                 "lds        r16,%0                \n\t"        //Wait for previous spm to complete
656
                                 "andi        r16,1           \n\t"
657
                                 "cpi        r16,1           \n\t"
658
                                 "breq        wait_spm5       \n\t"                                                                         
659
                                 "ldi        r16,0x11        \n\t"        //Re-enable RWW section
660
                                 "sts        %0,r16                \n\t"                                                                          
661
                                 "spm                        \n\t"                                                          
662
#ifdef __AVR_ATmega163__
663
                                 ".word 0xFFFF                \n\t"
664
                                 "nop                        \n\t"
665
#endif
666
                                 "same_page:                \n\t"                                                         
667
                                 "adiw        r30,2                \n\t"        //Next word in FLASH
668
                                 "sbiw        r24,2                \n\t"        //length-2
669
                                 "breq        final_write        \n\t"        //Finished
670
                                 "rjmp        length_loop        \n\t"
671
                                 "final_write:                \n\t"
672
                                 "cpi        r17,0                \n\t"
673
                                 "breq        block_done        \n\t"
674
                                 "adiw        r24,2                \n\t"        //length+2, fool above check on length after short page write
675
                                 "rjmp        write_page        \n\t"
676
                                 "block_done:                \n\t"
677
                                 "clr        __zero_reg__        \n\t"        //restore zero register
678
#if defined __AVR_ATmega168__  || __AVR_ATmega328P__
679
                                 : "=m" (SPMCSR) : "M" (PAGE_SIZE) : "r0","r16","r17","r24","r25","r28","r29","r30","r31"
680
#else
681
                                 : "=m" (SPMCR) : "M" (PAGE_SIZE) : "r0","r16","r17","r24","r25","r28","r29","r30","r31"
682
#endif
683
                                 );
684
                    /* Should really add a wait for RWW section to be enabled, don't actually need it since we never */
685
                    /* exit the bootloader without a power cycle anyhow */
686
                }
687
                putch(0x14);
688
                putch(0x10);
689
            }                
690
        }
691
    
692
693
        /* Read memory block mode, length is big endian.  */
694
        else if(ch=='t') {
695
            length.byte[1] = getch();
696
            length.byte[0] = getch();
697
#if defined __AVR_ATmega128__
698
            if (address.word>0x7FFF) flags.rampz = 1;                // No go with m256, FIXME
699
            else flags.rampz = 0;
700
#endif
701
            if (getch() == 'E') flags.eeprom = 1;
702
            else {
703
                flags.eeprom = 0;
704
                address.word = address.word << 1;                // address * 2 -> byte location
705
            }
706
            if (getch() == ' ') {                                // Command terminator
707
                putch(0x14);
708
                for (w=0;w < length.word;w++) {                        // Can handle odd and even lengths okay
709
                    if (flags.eeprom) {                                // Byte access EEPROM read
710
#if defined __AVR_ATmega168__  || __AVR_ATmega328P__
711
                        while(EECR & (1<<EEPE));
712
                        EEAR = (uint16_t)(void *)address.word;
713
                        EECR |= (1<<EERE);
714
                        putch(EEDR);
715
#else
716
                        putch(eeprom_read_byte((void *)address.word));
717
#endif
718
                        address.word++;
719
                    }
720
                    else {
721
722
                        if (!flags.rampz) putch(pgm_read_byte_near(address.word));
723
#if defined __AVR_ATmega128__
724
                        else putch(pgm_read_byte_far(address.word + 0x10000));
725
                        // Hmmmm, yuck  FIXME when m256 arrvies
726
#endif
727
                        address.word++;
728
                    }
729
                }
730
                putch(0x10);
731
            }
732
        }
733
734
735
        /* Get device signature bytes  */
736
        else if(ch=='u') {
737
            if (getch() == ' ') {
738
                putch(0x14);
739
                putch(SIG1);
740
                putch(SIG2);
741
                putch(SIG3);
742
                putch(0x10);
743
            }
744
        }
745
746
747
        /* Read oscillator calibration byte */
748
        else if(ch=='v') {
749
            byte_response(0x00);
750
        }
751
752
753
#ifdef MONITOR
754
755
        /* here come the extended monitor commands by Erik Lins */
756
757
        /* check for three times exclamation mark pressed */
758
        else if(ch=='!') {
759
            ch = getch();
760
            if(ch=='!') {
761
                ch = getch();
762
                if(ch=='!') {
763
764
#ifdef __AVR_ATmega128__
765
                    uint16_t extaddr;
766
#endif
767
                    uint8_t addrl, addrh;
768
769
#ifdef CRUMB128
770
                    PGM_P welcome = {"ATmegaBOOT / Crumb128 - (C) J.P.Kyle, E.Lins - 050815\n\r"};
771
#elif defined PROBOMEGA128
772
                    PGM_P welcome = {"ATmegaBOOT / PROBOmega128 - (C) J.P.Kyle, E.Lins - 050815\n\r"};
773
#elif defined SAVVY128
774
                    PGM_P welcome = {"ATmegaBOOT / Savvy128 - (C) J.P.Kyle, E.Lins - 050815\n\r"};
775
#endif
776
777
                    /* turn on LED */
778
                    LED_DDR |= _BV(LED);
779
                    LED_PORT &= ~_BV(LED);
780
781
                    /* print a welcome message and command overview */
782
                    for(i=0; welcome[i] != '\0'; ++i) {
783
                        putch(welcome[i]);
784
                    }
785
786
                    /* test for valid commands */
787
                    for(;;) {
788
                        putch('\n');
789
                        putch('\r');
790
                        putch(':');
791
                        putch(' ');
792
793
                        ch = getch();
794
                        putch(ch);
795
796
                        /* toggle LED */
797
                        if(ch == 't') {
798
                            if(bit_is_set(LED_PIN,LED)) {
799
                                LED_PORT &= ~_BV(LED);
800
                                putch('1');
801
                            } else {
802
                                LED_PORT |= _BV(LED);
803
                                putch('0');
804
                            }
805
806
                        } 
807
808
                        /* read byte from address */
809
                        else if(ch == 'r') {
810
                            ch = getch(); putch(ch);
811
                            addrh = gethex();
812
                            addrl = gethex();
813
                            putch('=');
814
                            ch = *(uint8_t *)((addrh << 8) + addrl);
815
                            puthex(ch);
816
                        }
817
818
                        /* write a byte to address  */
819
                        else if(ch == 'w') {
820
                            ch = getch(); putch(ch);
821
                            addrh = gethex();
822
                            addrl = gethex();
823
                            ch = getch(); putch(ch);
824
                            ch = gethex();
825
                            *(uint8_t *)((addrh << 8) + addrl) = ch;
826
827
                        }
828
829
                        /* read from uart and echo back */
830
                        else if(ch == 'u') {
831
                            for(;;) {
832
                                putch(getch());
833
                            }
834
                        }
835
#ifdef __AVR_ATmega128__
836
                        /* external bus loop  */
837
                        else if(ch == 'b') {
838
                            putch('b');
839
                            putch('u');
840
                            putch('s');
841
                            MCUCR = 0x80;
842
                            XMCRA = 0;
843
                            XMCRB = 0;
844
                            extaddr = 0x1100;
845
                            for(;;) {
846
                                ch = *(volatile uint8_t *)extaddr;
847
                                if(++extaddr == 0) {
848
                                    extaddr = 0x1100;
849
                                }
850
                            }
851
                        }
852
#endif
853
854
                        else if(ch == 'j') {
855
                            app_start();
856
                        }
857
858
                    }
859
                    /* end of monitor functions */
860
861
                }
862
            }
863
        }
864
        /* end of monitor */
865
#endif
866
867
868
    }
869
    /* end of forever loop */
870
871
}
872
873
874
char gethex(void) {
875
    char ah,al;
876
877
    ah = getch(); putch(ah);
878
    al = getch(); putch(al);
879
    if(ah >= 'a') {
880
        ah = ah - 'a' + 0x0a;
881
    } else if(ah >= '0') {
882
        ah -= '0';
883
    }
884
    if(al >= 'a') {
885
        al = al - 'a' + 0x0a;
886
    } else if(al >= '0') {
887
        al -= '0';
888
    }
889
    return (ah << 4) + al;
890
}
891
892
893
void puthex(char ch) {
894
    char ah,al;
895
896
    ah = (ch & 0xf0) >> 4;
897
    if(ah >= 0x0a) {
898
        ah = ah - 0x0a + 'a';
899
    } else {
900
        ah += '0';
901
    }
902
    al = (ch & 0x0f);
903
    if(al >= 0x0a) {
904
        al = al - 0x0a + 'a';
905
    } else {
906
        al += '0';
907
    }
908
    putch(ah);
909
    putch(al);
910
}
911
912
913
void putch(char ch)
914
{
915
#ifdef __AVR_ATmega128__
916
    if(bootuart == 1) {
917
        while (!(UCSR0A & _BV(UDRE0)));
918
        UDR0 = ch;
919
    }
920
    else if (bootuart == 2) {
921
        while (!(UCSR1A & _BV(UDRE1)));
922
        UDR1 = ch;
923
    }
924
#elif defined (__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
925
    while (!(UCSR0A & _BV(UDRE0)));
926
    UDR0 = ch;
927
#else
928
    /* m8,16,32,169,8515,8535,163 */
929
    while (!(UCSRA & _BV(UDRE)));
930
    UDR = ch;
931
#endif
932
}
933
934
935
char getch(void)
936
{
937
#ifdef __AVR_ATmega128__
938
    if(bootuart == 1) {
939
        while(!(UCSR0A & _BV(RXC0)));
940
        return UDR0;
941
    }
942
    else if(bootuart == 2) {
943
        while(!(UCSR1A & _BV(RXC1)));
944
        return UDR1;
945
    }
946
    return 0;
947
#elif defined (__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
948
    uint32_t count = 0;
949
    while(!(UCSR0A & _BV(RXC0))){
950
            /* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/               
951
            /* HACKME:: here is a good place to count times*/
952
            count++;
953
            if (count > MAX_TIME_COUNT)
954
                    app_start();
955
     }
956
    return UDR0;
957
#else
958
    /* m8,16,32,169,8515,8535,163 */
959
    uint32_t count = 0;
960
    while(!(UCSRA & _BV(RXC))){
961
            /* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/               
962
            /* HACKME:: here is a good place to count times*/
963
            count++;
964
            if (count > MAX_TIME_COUNT)
965
                    app_start();
966
     }
967
    return UDR;
968
#endif
969
}
970
971
972
void getNch(uint8_t count)
973
{
974
    uint8_t i;
975
    for(i=0;i<count;i++) {
976
#ifdef __AVR_ATmega128__
977
        if(bootuart == 1) {
978
            while(!(UCSR0A & _BV(RXC0)));
979
            UDR0;
980
        } 
981
        else if(bootuart == 2) {
982
            while(!(UCSR1A & _BV(RXC1)));
983
            UDR1;
984
        }
985
#elif (defined __AVR_ATmega168__) || defined(__AVR_ATmega328P__)
986
        while(!(UCSR0A & _BV(RXC0)));
987
        UDR0;
988
#else
989
        /* m8,16,32,169,8515,8535,163 */
990
           /* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/               
991
        //while(!(UCSRA & _BV(RXC)));
992
        //UDR;
993
    uint8_t i;
994
    for(i=0;i<count;i++) {
995
            getch(); // need to handle time out
996
    }
997
#endif                
998
    }
999
}
1000
1001
1002
void byte_response(uint8_t val)
1003
{
1004
    if (getch() == ' ') {
1005
        putch(0x14);
1006
        putch(val);
1007
        putch(0x10);
1008
    }
1009
}
1010
1011
1012
void nothing_response(void)
1013
{
1014
    if (getch() == ' ') {
1015
        putch(0x14);
1016
        putch(0x10);
1017
    }
1018
}
1019
1020
void flash_led(uint8_t count)
1021
{
1022
    /* flash onboard LED three times to signal entering of bootloader */
1023
    uint32_t l;
1024
1025
    if (count == 0) {
1026
      count = 3;
1027
    }
1028
    
1029
    for (i = 0; i < count; ++i) {
1030
        LED_PORT |= _BV(LED);
1031
        for(l = 0; l < (2 * F_CPU); ++l);
1032
        LED_PORT &= ~_BV(LED);
1033
        for(l = 0; l < (F_CPU / 5); ++l);
1034
    }
1035
}
1036
1037
1038
/* end of file ATmegaBOOT.c */