From 2d30c6588bd45d02a2ef6070cbe5b8007fb33a66 Mon Sep 17 00:00:00 2001
From: Joerg Wunsch <j@uriah.heep.sax.de>
Date: Fri, 16 Sep 2005 14:54:55 +0000
Subject: [PATCH] Improve the initializion sequence of the butterfly so it is
 more likely to synchronize with the device.

bug #9787 overview: avrdude 4.4.0 correct butterfly interface


git-svn-id: svn://svn.savannah.nongnu.org/avrdude/trunk@496 81a1dc3b-b13d-400b-aceb-764788c761c2
---
 avrdude/ChangeLog   |  5 +++++
 avrdude/butterfly.c | 33 ++++++++++++++++++++++-----------
 2 files changed, 27 insertions(+), 11 deletions(-)

diff --git a/avrdude/ChangeLog b/avrdude/ChangeLog
index ff0edc69..d9a3e243 100644
--- a/avrdude/ChangeLog
+++ b/avrdude/ChangeLog
@@ -1,3 +1,8 @@
+2005-09-16  Joerg Wunsch <j@uriah.heep.sax.de>
+
+	* butterfly.c: improve the butterfly initialization so it is more likely
+	to synchonize; [bug #9787: avrdude 4.4.0 correct butterfly interface]
+
 2005-09-14  Joerg Wunsch <j@uriah.heep.sax.de>
 
 	* avrdude.conf.in: add a jtag2slow programmer alias, and make
diff --git a/avrdude/butterfly.c b/avrdude/butterfly.c
index 358f660c..32809323 100644
--- a/avrdude/butterfly.c
+++ b/avrdude/butterfly.c
@@ -235,15 +235,25 @@ static int butterfly_initialize(PROGRAMMER * pgm, AVRPART * p)
    * Send some ESC to activate butterfly bootloader.  This is not needed
    * for plain avr109 bootloaders but does not harm there either.
    */
-  butterfly_send(pgm, "\033\033\033\033", 4);
-  butterfly_drain(pgm, 0);
-
-  /* Get the programmer identifier. Programmer returns exactly 7 chars
-     _without_ the null.*/
-
-  butterfly_send(pgm, "S", 1);
-  memset (id, 0, sizeof(id));
-  butterfly_recv(pgm, id, sizeof(id)-1);
+  fprintf(stderr, "Connecting to programmer: ");
+  do {
+    putc('.', stderr);
+    butterfly_send(pgm, "\033", 1);
+    butterfly_drain(pgm, 0);
+    butterfly_send(pgm, "S", 1);
+    butterfly_recv(pgm, &c, 1);
+    if (c != '?') {
+        putc('\n', stderr);
+        /*
+         * Got a useful response, continue getting the programmer
+         * identifier. Programmer returns exactly 7 chars _without_
+         * the null.
+         */
+      id[0] = c;
+      butterfly_recv(pgm, &id[1], sizeof(id)-2);
+      id[sizeof(id)-1] = '\0';
+    }
+  } while (c == '?');
 
   /* Get the HW and SW versions to see if the programmer is present. */
 
@@ -327,6 +337,9 @@ static int butterfly_initialize(PROGRAMMER * pgm, AVRPART * p)
   butterfly_send(pgm, buf, 2);
   butterfly_vfy_cmd_sent(pgm, "select device");
 
+  if (dev_supported)
+      butterfly_enter_prog_mode(pgm);
+
   return dev_supported? 0: -1;
 }
 
@@ -346,8 +359,6 @@ static void butterfly_enable(PROGRAMMER * pgm)
 {
   no_show_func_info();
 
-  butterfly_enter_prog_mode(pgm);
-
   return;
 }