Contiki 3.x
bootloader.c
1 #include "bootloader.h"
2 #include "dev/watchdog.h"
3 #include <util/delay.h>
4 #include <avr/wdt.h>
5 #include <avr/interrupt.h>
6 #include <avr/pgmspace.h>
7 #include "dev/usb/usb_drv.h"
8 #include <avr/pgmspace.h>
9 #include <avr/interrupt.h>
10 #include <avr/eeprom.h>
11 
12 /* MCUSR is a deprecated name but older avr-libc versions may define it */
13 #if !defined (MCUCSR)
14 # if defined (MCUSR)
15 # warning *** MCUCSR not defined, using MCUSR instead ***
16 # define MCUCSR MCUSR
17 # endif
18 #endif
19 
20 #ifndef EEPROM_MAGIC_BYTE_ADDR
21 #define EEPROM_MAGIC_BYTE_ADDR (uint8_t*)(E2END-3)
22 #endif
23 
24 volatile uint32_t Boot_Key ATTR_NO_INIT;
25 
26 extern void Bootloader_Jump_Check(void) ATTR_INIT_SECTION(3);
27 
28 bool
29 bootloader_is_present(void)
30 {
31 #if defined(BOOTLOADER_START_ADDRESS)
32  return pgm_read_word_far(BOOTLOADER_START_ADDRESS) != 0xFFFF;
33 #else
34  return false;
35 #endif
36 }
37 
38 void
39 Jump_To_Bootloader(void)
40 {
41  /* Disable all interrupts */
42  cli();
43 
44 #ifdef UDCON
45  /* If USB is used, detach from the bus */
46  Usb_detach();
47 
48  uint8_t i;
49 
50  /* Wait two seconds for the USB detachment to register on the host */
51  for(i = 0; i < 200; i++) {
52  _delay_ms(10);
54  }
55 #endif
56 
57  /* Set the bootloader key to the magic value and force a reset */
58  Boot_Key = MAGIC_BOOT_KEY;
59 
60  eeprom_write_byte(EEPROM_MAGIC_BYTE_ADDR, 0xFF);
61 
62  /* Enable interrupts */
63  sei();
64 
66 }
67 
68 void
69 Bootloader_Jump_Check(void)
70 {
71  /* If the reset source was the bootloader and the key is correct,
72  * clear it and jump to the bootloader
73  */
74  if(MCUCSR & (1 << WDRF)) {
75  MCUCSR = 0;
76  if(Boot_Key == MAGIC_BOOT_KEY) {
77  Boot_Key = 0;
78  wdt_disable();
79 
80  /* Disable all interrupts */
81  cli();
82 
83  eeprom_write_byte(EEPROM_MAGIC_BYTE_ADDR, 0xFF);
84 
85  /* Enable interrupts */
86  sei();
87 
88  ((void (*)(void))(BOOTLOADER_START_ADDRESS)) ();
89  } else {
90  /* The watchdog fired. Probably means we
91  * crashed. Wait two seconds before continuing.
92  */
93 
94  Boot_Key++;
95  uint8_t i;
96 
97  for(i = 0; i < 200; i++) {
98  _delay_ms(10);
100  }
101  }
102  } else {
103  Boot_Key = MAGIC_BOOT_KEY - 4;
104  }
105 }
#define Usb_detach()
detaches from USB bus
Definition: usb_drv.h:367
This file contains the USB driver routines.
void watchdog_reboot(void)
Keeps control until the WDT throws a reset signal.
Definition: watchdog.c:128
void watchdog_periodic(void)
Writes the WDT clear sequence.
Definition: watchdog.c:64