optiboot.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /**********************************************************/
  2. /* Optiboot bootloader for Arduino */
  3. /* */
  4. /* http://optiboot.googlecode.com */
  5. /* */
  6. /* Arduino-maintained version : See README.TXT */
  7. /* http://code.google.com/p/arduino/ */
  8. /* */
  9. /* Heavily optimised bootloader that is faster and */
  10. /* smaller than the Arduino standard bootloader */
  11. /* */
  12. /* Enhancements: */
  13. /* Fits in 512 bytes, saving 1.5K of code space */
  14. /* Background page erasing speeds up programming */
  15. /* Higher baud rate speeds up programming */
  16. /* Written almost entirely in C */
  17. /* Customisable timeout with accurate timeconstant */
  18. /* Optional virtual UART. No hardware UART required. */
  19. /* Optional virtual boot partition for devices without. */
  20. /* */
  21. /* What you lose: */
  22. /* Implements a skeleton STK500 protocol which is */
  23. /* missing several features including EEPROM */
  24. /* programming and non-page-aligned writes */
  25. /* High baud rate breaks compatibility with standard */
  26. /* Arduino flash settings */
  27. /* */
  28. /* Fully supported: */
  29. /* ATmega168 based devices (Diecimila etc) */
  30. /* ATmega328P based devices (Duemilanove etc) */
  31. /* */
  32. /* Alpha test */
  33. /* ATmega1280 based devices (Arduino Mega) */
  34. /* */
  35. /* Work in progress: */
  36. /* ATmega644P based devices (Sanguino) */
  37. /* ATtiny84 based devices (Luminet) */
  38. /* */
  39. /* Does not support: */
  40. /* USB based devices (eg. Teensy) */
  41. /* */
  42. /* Assumptions: */
  43. /* The code makes several assumptions that reduce the */
  44. /* code size. They are all true after a hardware reset, */
  45. /* but may not be true if the bootloader is called by */
  46. /* other means or on other hardware. */
  47. /* No interrupts can occur */
  48. /* UART and Timer 1 are set to their reset state */
  49. /* SP points to RAMEND */
  50. /* */
  51. /* Code builds on code, libraries and optimisations from: */
  52. /* stk500boot.c by Jason P. Kyle */
  53. /* Arduino bootloader http://arduino.cc */
  54. /* Spiff's 1K bootloader http://spiffie.org/know/arduino_1k_bootloader/bootloader.shtml */
  55. /* avr-libc project http://nongnu.org/avr-libc */
  56. /* Adaboot http://www.ladyada.net/library/arduino/bootloader.html */
  57. /* AVR305 Atmel Application Note */
  58. /* */
  59. /* This program is free software; you can redistribute it */
  60. /* and/or modify it under the terms of the GNU General */
  61. /* Public License as published by the Free Software */
  62. /* Foundation; either version 2 of the License, or */
  63. /* (at your option) any later version. */
  64. /* */
  65. /* This program is distributed in the hope that it will */
  66. /* be useful, but WITHOUT ANY WARRANTY; without even the */
  67. /* implied warranty of MERCHANTABILITY or FITNESS FOR A */
  68. /* PARTICULAR PURPOSE. See the GNU General Public */
  69. /* License for more details. */
  70. /* */
  71. /* You should have received a copy of the GNU General */
  72. /* Public License along with this program; if not, write */
  73. /* to the Free Software Foundation, Inc., */
  74. /* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
  75. /* */
  76. /* Licence can be viewed at */
  77. /* http://www.fsf.org/licenses/gpl.txt */
  78. /* */
  79. /**********************************************************/
  80. /**********************************************************/
  81. /* */
  82. /* Optional defines: */
  83. /* */
  84. /**********************************************************/
  85. /* */
  86. /* BIG_BOOT: */
  87. /* Build a 1k bootloader, not 512 bytes. This turns on */
  88. /* extra functionality. */
  89. /* */
  90. /* BAUD_RATE: */
  91. /* Set bootloader baud rate. */
  92. /* */
  93. /* LUDICROUS_SPEED: */
  94. /* 230400 baud :-) */
  95. /* */
  96. /* SOFT_UART: */
  97. /* Use AVR305 soft-UART instead of hardware UART. */
  98. /* */
  99. /* LED_START_FLASHES: */
  100. /* Number of LED flashes on bootup. */
  101. /* */
  102. /* LED_DATA_FLASH: */
  103. /* Flash LED when transferring data. For boards without */
  104. /* TX or RX LEDs, or for people who like blinky lights. */
  105. /* */
  106. /* SUPPORT_EEPROM: */
  107. /* Support reading and writing from EEPROM. This is not */
  108. /* used by Arduino, so off by default. */
  109. /* */
  110. /* TIMEOUT_MS: */
  111. /* Bootloader timeout period, in milliseconds. */
  112. /* 500,1000,2000,4000,8000 supported. */
  113. /* */
  114. /**********************************************************/
  115. /**********************************************************/
  116. /* Version Numbers! */
  117. /* */
  118. /* Arduino Optiboot now includes this Version number in */
  119. /* the source and object code. */
  120. /* */
  121. /* Version 3 was released as zip from the optiboot */
  122. /* repository and was distributed with Arduino 0022. */
  123. /* Version 4 starts with the arduino repository commit */
  124. /* that brought the arduino repository up-to-date with */
  125. /* the optiboot source tree changes since v3. */
  126. /* */
  127. /**********************************************************/
  128. /**********************************************************/
  129. /* Edit History: */
  130. /* */
  131. /* Jan 2012: */
  132. /* 4.5 WestfW: fix NRWW value for m1284. */
  133. /* 4.4 WestfW: use attribute OS_main instead of naked for */
  134. /* main(). This allows optimizations that we */
  135. /* count on, which are prohibited in naked */
  136. /* functions due to PR42240. (keeps us less */
  137. /* than 512 bytes when compiler is gcc4.5 */
  138. /* (code from 4.3.2 remains the same.) */
  139. /* 4.4 WestfW and Maniacbug: Add m1284 support. This */
  140. /* does not change the 328 binary, so the */
  141. /* version number didn't change either. (?) */
  142. /* June 2011: */
  143. /* 4.4 WestfW: remove automatic soft_uart detect (didn't */
  144. /* know what it was doing or why.) Added a */
  145. /* check of the calculated BRG value instead. */
  146. /* Version stays 4.4; existing binaries are */
  147. /* not changed. */
  148. /* 4.4 WestfW: add initialization of address to keep */
  149. /* the compiler happy. Change SC'ed targets. */
  150. /* Return the SW version via READ PARAM */
  151. /* 4.3 WestfW: catch framing errors in getch(), so that */
  152. /* AVRISP works without HW kludges. */
  153. /* http://code.google.com/p/arduino/issues/detail?id=368n*/
  154. /* 4.2 WestfW: reduce code size, fix timeouts, change */
  155. /* verifySpace to use WDT instead of appstart */
  156. /* 4.1 WestfW: put version number in binary. */
  157. /**********************************************************/
  158. #define OPTIBOOT_MAJVER 4
  159. #define OPTIBOOT_MINVER 5
  160. #define MAKESTR(a) #a
  161. #define MAKEVER(a, b) MAKESTR(a*256+b)
  162. asm(" .section .version\n"
  163. "optiboot_version: .word " MAKEVER(OPTIBOOT_MAJVER, OPTIBOOT_MINVER) "\n"
  164. " .section .text\n");
  165. #include <inttypes.h>
  166. #include <avr/io.h>
  167. #include <avr/pgmspace.h>
  168. // <avr/boot.h> uses sts instructions, but this version uses out instructions
  169. // This saves cycles and program memory.
  170. #include "boot.h"
  171. // We don't use <avr/wdt.h> as those routines have interrupt overhead we don't need.
  172. #include "pin_defs.h"
  173. #include "stk500.h"
  174. #ifndef LED_START_FLASHES
  175. #define LED_START_FLASHES 0
  176. #endif
  177. #ifdef LUDICROUS_SPEED
  178. #define BAUD_RATE 230400L
  179. #endif
  180. /* set the UART baud rate defaults */
  181. #ifndef BAUD_RATE
  182. #if F_CPU >= 8000000L
  183. #define BAUD_RATE 115200L // Highest rate Avrdude win32 will support
  184. #elsif F_CPU >= 1000000L
  185. #define BAUD_RATE 9600L // 19200 also supported, but with significant error
  186. #elsif F_CPU >= 128000L
  187. #define BAUD_RATE 4800L // Good for 128kHz internal RC
  188. #else
  189. #define BAUD_RATE 1200L // Good even at 32768Hz
  190. #endif
  191. #endif
  192. #if 0
  193. /* Switch in soft UART for hard baud rates */
  194. /*
  195. * I don't understand what this was supposed to accomplish, where the
  196. * constant "280" came from, or why automatically (and perhaps unexpectedly)
  197. * switching to a soft uart is a good thing, so I'm undoing this in favor
  198. * of a range check using the same calc used to config the BRG...
  199. */
  200. #if (F_CPU/BAUD_RATE) > 280 // > 57600 for 16MHz
  201. #ifndef SOFT_UART
  202. #define SOFT_UART
  203. #endif
  204. #endif
  205. #else // 0
  206. #if (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 > 250
  207. #error Unachievable baud rate (too slow) BAUD_RATE
  208. #endif // baud rate slow check
  209. #if (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 < 3
  210. #error Unachievable baud rate (too fast) BAUD_RATE
  211. #endif // baud rate fastn check
  212. #endif
  213. /* Watchdog settings */
  214. #define WATCHDOG_OFF (0)
  215. #define WATCHDOG_16MS (_BV(WDE))
  216. #define WATCHDOG_32MS (_BV(WDP0) | _BV(WDE))
  217. #define WATCHDOG_64MS (_BV(WDP1) | _BV(WDE))
  218. #define WATCHDOG_125MS (_BV(WDP1) | _BV(WDP0) | _BV(WDE))
  219. #define WATCHDOG_250MS (_BV(WDP2) | _BV(WDE))
  220. #define WATCHDOG_500MS (_BV(WDP2) | _BV(WDP0) | _BV(WDE))
  221. #define WATCHDOG_1S (_BV(WDP2) | _BV(WDP1) | _BV(WDE))
  222. #define WATCHDOG_2S (_BV(WDP2) | _BV(WDP1) | _BV(WDP0) | _BV(WDE))
  223. #ifndef __AVR_ATmega8__
  224. #define WATCHDOG_4S (_BV(WDP3) | _BV(WDE))
  225. #define WATCHDOG_8S (_BV(WDP3) | _BV(WDP0) | _BV(WDE))
  226. #endif
  227. /* Function Prototypes */
  228. /* The main function is in init9, which removes the interrupt vector table */
  229. /* we don't need. It is also 'naked', which means the compiler does not */
  230. /* generate any entry or exit code itself. */
  231. int main(void) __attribute__ ((OS_main)) __attribute__ ((section (".init9")));
  232. void putch(char);
  233. uint8_t getch(void);
  234. static inline void getNch(uint8_t); /* "static inline" is a compiler hint to reduce code size */
  235. void verifySpace();
  236. static inline void flash_led(uint8_t);
  237. uint8_t getLen();
  238. static inline void watchdogReset();
  239. void watchdogConfig(uint8_t x);
  240. #ifdef SOFT_UART
  241. void uartDelay() __attribute__ ((naked));
  242. #endif
  243. void appStart() __attribute__ ((naked));
  244. /*
  245. * NRWW memory
  246. * Addresses below NRWW (Non-Read-While-Write) can be programmed while
  247. * continuing to run code from flash, slightly speeding up programming
  248. * time. Beware that Atmel data sheets specify this as a WORD address,
  249. * while optiboot will be comparing against a 16-bit byte address. This
  250. * means that on a part with 128kB of memory, the upper part of the lower
  251. * 64k will get NRWW processing as well, even though it doesn't need it.
  252. * That's OK. In fact, you can disable the overlapping processing for
  253. * a part entirely by setting NRWWSTART to zero. This reduces code
  254. * space a bit, at the expense of being slightly slower, overall.
  255. *
  256. * RAMSTART should be self-explanatory. It's bigger on parts with a
  257. * lot of peripheral registers.
  258. */
  259. #if defined(__AVR_ATmega168__)
  260. #define RAMSTART (0x100)
  261. #define NRWWSTART (0x3800)
  262. #elif defined(__AVR_ATmega328P__)
  263. #define RAMSTART (0x100)
  264. #define NRWWSTART (0x7000)
  265. #elif defined (__AVR_ATmega644P__)
  266. #define RAMSTART (0x100)
  267. #define NRWWSTART (0xE000)
  268. #elif defined (__AVR_ATmega1284P__)
  269. #define RAMSTART (0x100)
  270. #define NRWWSTART (0xE000)
  271. #elif defined(__AVR_ATtiny84__)
  272. #define RAMSTART (0x100)
  273. #define NRWWSTART (0x0000)
  274. #elif defined(__AVR_ATmega1280__)
  275. #define RAMSTART (0x200)
  276. #define NRWWSTART (0xE000)
  277. #elif defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__)
  278. #define RAMSTART (0x100)
  279. #define NRWWSTART (0x1800)
  280. #endif
  281. /* C zero initialises all global variables. However, that requires */
  282. /* These definitions are NOT zero initialised, but that doesn't matter */
  283. /* This allows us to drop the zero init code, saving us memory */
  284. #define buff ((uint8_t*)(RAMSTART))
  285. #ifdef VIRTUAL_BOOT_PARTITION
  286. #define rstVect (*(uint16_t*)(RAMSTART+SPM_PAGESIZE*2+4))
  287. #define wdtVect (*(uint16_t*)(RAMSTART+SPM_PAGESIZE*2+6))
  288. #endif
  289. /* main program starts here */
  290. int main(void) {
  291. uint8_t ch;
  292. /*
  293. * Making these local and in registers prevents the need for initializing
  294. * them, and also saves space because code no longer stores to memory.
  295. * (initializing address keeps the compiler happy, but isn't really
  296. * necessary, and uses 4 bytes of flash.)
  297. */
  298. register uint16_t address = 0;
  299. register uint8_t length;
  300. // After the zero init loop, this is the first code to run.
  301. //
  302. // This code makes the following assumptions:
  303. // No interrupts will execute
  304. // SP points to RAMEND
  305. // r1 contains zero
  306. //
  307. // If not, uncomment the following instructions:
  308. // cli();
  309. asm volatile ("clr __zero_reg__");
  310. #ifdef __AVR_ATmega8__
  311. SP=RAMEND; // This is done by hardware reset
  312. #endif
  313. // Adaboot no-wait mod
  314. ch = MCUSR;
  315. MCUSR = 0;
  316. if (!(ch & _BV(EXTRF))) appStart();
  317. #if LED_START_FLASHES > 0
  318. // Set up Timer 1 for timeout counter
  319. TCCR1B = _BV(CS12) | _BV(CS10); // div 1024
  320. #endif
  321. #ifndef SOFT_UART
  322. #ifdef __AVR_ATmega8__
  323. UCSRA = _BV(U2X); //Double speed mode USART
  324. UCSRB = _BV(RXEN) | _BV(TXEN); // enable Rx & Tx
  325. UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0); // config USART; 8N1
  326. UBRRL = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
  327. #else
  328. UCSR0A = _BV(U2X0); //Double speed mode USART0
  329. UCSR0B = _BV(RXEN0) | _BV(TXEN0);
  330. UCSR0C = _BV(UCSZ00) | _BV(UCSZ01);
  331. UBRR0L = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
  332. #endif
  333. #endif
  334. // Set up watchdog to trigger after 500ms
  335. watchdogConfig(WATCHDOG_1S);
  336. /* Set LED pin as output */
  337. LED_DDR |= _BV(LED);
  338. #ifdef SOFT_UART
  339. /* Set TX pin as output */
  340. UART_DDR |= _BV(UART_TX_BIT);
  341. #endif
  342. #if LED_START_FLASHES > 0
  343. /* Flash onboard LED to signal entering of bootloader */
  344. flash_led(LED_START_FLASHES * 2);
  345. #endif
  346. /* Forever loop */
  347. for (;;) {
  348. /* get character from UART */
  349. ch = getch();
  350. if(ch == STK_GET_PARAMETER) {
  351. unsigned char which = getch();
  352. verifySpace();
  353. if (which == 0x82) {
  354. /*
  355. * Send optiboot version as "minor SW version"
  356. */
  357. putch(OPTIBOOT_MINVER);
  358. } else if (which == 0x81) {
  359. putch(OPTIBOOT_MAJVER);
  360. } else {
  361. /*
  362. * GET PARAMETER returns a generic 0x03 reply for
  363. * other parameters - enough to keep Avrdude happy
  364. */
  365. putch(0x03);
  366. }
  367. }
  368. else if(ch == STK_SET_DEVICE) {
  369. // SET DEVICE is ignored
  370. getNch(20);
  371. }
  372. else if(ch == STK_SET_DEVICE_EXT) {
  373. // SET DEVICE EXT is ignored
  374. getNch(5);
  375. }
  376. else if(ch == STK_LOAD_ADDRESS) {
  377. // LOAD ADDRESS
  378. uint16_t newAddress;
  379. newAddress = getch();
  380. newAddress = (newAddress & 0xff) | (getch() << 8);
  381. #ifdef RAMPZ
  382. // Transfer top bit to RAMPZ
  383. RAMPZ = (newAddress & 0x8000) ? 1 : 0;
  384. #endif
  385. newAddress += newAddress; // Convert from word address to byte address
  386. address = newAddress;
  387. verifySpace();
  388. }
  389. else if(ch == STK_UNIVERSAL) {
  390. // UNIVERSAL command is ignored
  391. getNch(4);
  392. putch(0x00);
  393. }
  394. /* Write memory, length is big endian and is in bytes */
  395. else if(ch == STK_PROG_PAGE) {
  396. // PROGRAM PAGE - we support flash programming only, not EEPROM
  397. uint8_t *bufPtr;
  398. uint16_t addrPtr;
  399. getch(); /* getlen() */
  400. length = getch();
  401. getch();
  402. // If we are in RWW section, immediately start page erase
  403. if (address < NRWWSTART) __boot_page_erase_short((uint16_t)(void*)address);
  404. // While that is going on, read in page contents
  405. bufPtr = buff;
  406. do *bufPtr++ = getch();
  407. while (--length);
  408. // If we are in NRWW section, page erase has to be delayed until now.
  409. // Todo: Take RAMPZ into account
  410. if (address >= NRWWSTART) __boot_page_erase_short((uint16_t)(void*)address);
  411. // Read command terminator, start reply
  412. verifySpace();
  413. // If only a partial page is to be programmed, the erase might not be complete.
  414. // So check that here
  415. boot_spm_busy_wait();
  416. #ifdef VIRTUAL_BOOT_PARTITION
  417. if ((uint16_t)(void*)address == 0) {
  418. // This is the reset vector page. We need to live-patch the code so the
  419. // bootloader runs.
  420. //
  421. // Move RESET vector to WDT vector
  422. uint16_t vect = buff[0] | (buff[1]<<8);
  423. rstVect = vect;
  424. wdtVect = buff[8] | (buff[9]<<8);
  425. vect -= 4; // Instruction is a relative jump (rjmp), so recalculate.
  426. buff[8] = vect & 0xff;
  427. buff[9] = vect >> 8;
  428. // Add jump to bootloader at RESET vector
  429. buff[0] = 0x7f;
  430. buff[1] = 0xce; // rjmp 0x1d00 instruction
  431. }
  432. #endif
  433. // Copy buffer into programming buffer
  434. bufPtr = buff;
  435. addrPtr = (uint16_t)(void*)address;
  436. ch = SPM_PAGESIZE / 2;
  437. do {
  438. uint16_t a;
  439. a = *bufPtr++;
  440. a |= (*bufPtr++) << 8;
  441. __boot_page_fill_short((uint16_t)(void*)addrPtr,a);
  442. addrPtr += 2;
  443. } while (--ch);
  444. // Write from programming buffer
  445. __boot_page_write_short((uint16_t)(void*)address);
  446. boot_spm_busy_wait();
  447. #if defined(RWWSRE)
  448. // Reenable read access to flash
  449. boot_rww_enable();
  450. #endif
  451. }
  452. /* Read memory block mode, length is big endian. */
  453. else if(ch == STK_READ_PAGE) {
  454. // READ PAGE - we only read flash
  455. getch(); /* getlen() */
  456. length = getch();
  457. getch();
  458. verifySpace();
  459. #ifdef VIRTUAL_BOOT_PARTITION
  460. do {
  461. // Undo vector patch in bottom page so verify passes
  462. if (address == 0) ch=rstVect & 0xff;
  463. else if (address == 1) ch=rstVect >> 8;
  464. else if (address == 8) ch=wdtVect & 0xff;
  465. else if (address == 9) ch=wdtVect >> 8;
  466. else ch = pgm_read_byte_near(address);
  467. address++;
  468. putch(ch);
  469. } while (--length);
  470. #else
  471. #ifdef RAMPZ
  472. // Since RAMPZ should already be set, we need to use EPLM directly.
  473. // do putch(pgm_read_byte_near(address++));
  474. // while (--length);
  475. do {
  476. uint8_t result;
  477. __asm__ ("elpm %0,Z\n":"=r"(result):"z"(address));
  478. putch(result);
  479. address++;
  480. }
  481. while (--length);
  482. #else
  483. do putch(pgm_read_byte_near(address++));
  484. while (--length);
  485. #endif
  486. #endif
  487. }
  488. /* Get device signature bytes */
  489. else if(ch == STK_READ_SIGN) {
  490. // READ SIGN - return what Avrdude wants to hear
  491. verifySpace();
  492. putch(SIGNATURE_0);
  493. putch(SIGNATURE_1);
  494. putch(SIGNATURE_2);
  495. }
  496. else if (ch == STK_LEAVE_PROGMODE) { /* 'Q' */
  497. // Adaboot no-wait mod
  498. watchdogConfig(WATCHDOG_16MS);
  499. verifySpace();
  500. }
  501. else {
  502. // This covers the response to commands like STK_ENTER_PROGMODE
  503. verifySpace();
  504. }
  505. putch(STK_OK);
  506. }
  507. }
  508. void putch(char ch) {
  509. #ifndef SOFT_UART
  510. while (!(UCSR0A & _BV(UDRE0)));
  511. UDR0 = ch;
  512. #else
  513. __asm__ __volatile__ (
  514. " com %[ch]\n" // ones complement, carry set
  515. " sec\n"
  516. "1: brcc 2f\n"
  517. " cbi %[uartPort],%[uartBit]\n"
  518. " rjmp 3f\n"
  519. "2: sbi %[uartPort],%[uartBit]\n"
  520. " nop\n"
  521. "3: rcall uartDelay\n"
  522. " rcall uartDelay\n"
  523. " lsr %[ch]\n"
  524. " dec %[bitcnt]\n"
  525. " brne 1b\n"
  526. :
  527. :
  528. [bitcnt] "d" (10),
  529. [ch] "r" (ch),
  530. [uartPort] "I" (_SFR_IO_ADDR(UART_PORT)),
  531. [uartBit] "I" (UART_TX_BIT)
  532. :
  533. "r25"
  534. );
  535. #endif
  536. }
  537. uint8_t getch(void) {
  538. uint8_t ch;
  539. #ifdef LED_DATA_FLASH
  540. #ifdef __AVR_ATmega8__
  541. LED_PORT ^= _BV(LED);
  542. #else
  543. LED_PIN |= _BV(LED);
  544. #endif
  545. #endif
  546. #ifdef SOFT_UART
  547. __asm__ __volatile__ (
  548. "1: sbic %[uartPin],%[uartBit]\n" // Wait for start edge
  549. " rjmp 1b\n"
  550. " rcall uartDelay\n" // Get to middle of start bit
  551. "2: rcall uartDelay\n" // Wait 1 bit period
  552. " rcall uartDelay\n" // Wait 1 bit period
  553. " clc\n"
  554. " sbic %[uartPin],%[uartBit]\n"
  555. " sec\n"
  556. " dec %[bitCnt]\n"
  557. " breq 3f\n"
  558. " ror %[ch]\n"
  559. " rjmp 2b\n"
  560. "3:\n"
  561. :
  562. [ch] "=r" (ch)
  563. :
  564. [bitCnt] "d" (9),
  565. [uartPin] "I" (_SFR_IO_ADDR(UART_PIN)),
  566. [uartBit] "I" (UART_RX_BIT)
  567. :
  568. "r25"
  569. );
  570. #else
  571. while(!(UCSR0A & _BV(RXC0)))
  572. ;
  573. if (!(UCSR0A & _BV(FE0))) {
  574. /*
  575. * A Framing Error indicates (probably) that something is talking
  576. * to us at the wrong bit rate. Assume that this is because it
  577. * expects to be talking to the application, and DON'T reset the
  578. * watchdog. This should cause the bootloader to abort and run
  579. * the application "soon", if it keeps happening. (Note that we
  580. * don't care that an invalid char is returned...)
  581. */
  582. watchdogReset();
  583. }
  584. ch = UDR0;
  585. #endif
  586. #ifdef LED_DATA_FLASH
  587. #ifdef __AVR_ATmega8__
  588. LED_PORT ^= _BV(LED);
  589. #else
  590. LED_PIN |= _BV(LED);
  591. #endif
  592. #endif
  593. return ch;
  594. }
  595. #ifdef SOFT_UART
  596. // AVR305 equation: #define UART_B_VALUE (((F_CPU/BAUD_RATE)-23)/6)
  597. // Adding 3 to numerator simulates nearest rounding for more accurate baud rates
  598. #define UART_B_VALUE (((F_CPU/BAUD_RATE)-20)/6)
  599. #if UART_B_VALUE > 255
  600. #error Baud rate too slow for soft UART
  601. #endif
  602. void uartDelay() {
  603. __asm__ __volatile__ (
  604. "ldi r25,%[count]\n"
  605. "1:dec r25\n"
  606. "brne 1b\n"
  607. "ret\n"
  608. ::[count] "M" (UART_B_VALUE)
  609. );
  610. }
  611. #endif
  612. void getNch(uint8_t count) {
  613. do getch(); while (--count);
  614. verifySpace();
  615. }
  616. void verifySpace() {
  617. if (getch() != CRC_EOP) {
  618. watchdogConfig(WATCHDOG_16MS); // shorten WD timeout
  619. while (1) // and busy-loop so that WD causes
  620. ; // a reset and app start.
  621. }
  622. putch(STK_INSYNC);
  623. }
  624. #if LED_START_FLASHES > 0
  625. void flash_led(uint8_t count) {
  626. do {
  627. TCNT1 = -(F_CPU/(1024*16));
  628. TIFR1 = _BV(TOV1);
  629. while(!(TIFR1 & _BV(TOV1)));
  630. #ifdef __AVR_ATmega8__
  631. LED_PORT ^= _BV(LED);
  632. #else
  633. LED_PIN |= _BV(LED);
  634. #endif
  635. watchdogReset();
  636. } while (--count);
  637. }
  638. #endif
  639. // Watchdog functions. These are only safe with interrupts turned off.
  640. void watchdogReset() {
  641. __asm__ __volatile__ (
  642. "wdr\n"
  643. );
  644. }
  645. void watchdogConfig(uint8_t x) {
  646. WDTCSR = _BV(WDCE) | _BV(WDE);
  647. WDTCSR = x;
  648. }
  649. void appStart() {
  650. watchdogConfig(WATCHDOG_OFF);
  651. __asm__ __volatile__ (
  652. #ifdef VIRTUAL_BOOT_PARTITION
  653. // Jump to WDT vector
  654. "ldi r30,4\n"
  655. "clr r31\n"
  656. #else
  657. // Jump to RST vector
  658. "clr r30\n"
  659. "clr r31\n"
  660. #endif
  661. "ijmp\n"
  662. );
  663. }